Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top