1

Look at the following code:

char chs[100] = "Hello World";
char token[100];
int pos = -1;
while((current = chs[++pos]) != '"'){
      strcat(token, &current);
}

But the output is :

H\001e\001l\001l\001o\001 \001W\001o\001r\001l\001d

Any ideas?

Foredoomed
  • 2,219
  • 2
  • 21
  • 39
  • @mbratch The output is supposed to be Hello World – Foredoomed May 26 '13 at 02:09
  • @Foredoomed You're trying to strip the quotes surrounding the string literal? The quotes are not actually a part of the string to begin with! Maybe you should start by reading a [book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Praetorian May 26 '13 at 02:10
  • @Foredoomed, but is this just supposed to be a string copy from `chs` to `token`? If so, then that's what `strcpy` is for. You would just do `strcpy(token, chs);` and be done. No loop required. Or is some other purpose intended? If you want to use `strcat`, it requires both string parameters to be zero terminated. So you'd at least need to set `token[0] = '\0'` to start before the loop, as I had mentioned. – lurker May 26 '13 at 02:19

3 Answers3

2

You have undefined behavior

Since your current is not declared, I'm guessing it is some uninitialized character. Your current = chs[++pos]) sets the character, but strcat(token, &current); want current to be a string, so you are getting some junk saved after the variable current. Please post more of your sample code for further analysis

BTW '"' looks wrong C

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
2

strcat() needs a null-terminated string as it's input. so strcat(token, &current) will start reading at the address of current and keep going until it finds a null. Just by chance, what you had in memory after current was "\001", so each time you did strcat it copied all that into token.

You should do char current[] = "\0\0" and then assign it with current[0] = chs[++pos]. That way current will always have that null termination.

0

Making minimal changes this is a working version of your code:

#include <string.h>
#include <stdio.h>

int main()
{
    char current[2] = { 0x0, 0x0 }; // Will be null terminated
    char chs[100] = "Hello World";
    char token[100] ;
    int pos = -1;  // Destination of strcat must also be null terminated

    token[0] = '\0' ;

    // String literals does not actually have " in memory they end in \0
    while((current[0] = chs[++pos]) != '\0')
    {
            strcat(token, &current[0]); // Take the address of the first char in current                      
    }   

    printf("%s\n", token ) ;

    return 0 ;
}

strcat expects both the source and destination to be null terminated strings. In your case it looks like current just ended up having a \001 followed by a null terminator after it in memory.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740