nocturne nocturne - 2 months ago 16
C Question

Formatted vs unformatted string C

I have a

char * temp_string
where I keep these chars:
Hello\nWor'ld\\\042
including
\0
at the end.

This is the way I make my string:

char * addDataChunk(char * data,char c)
{
char * p;
if(data==NULL)
{
if(!(data=(char*)malloc(sizeof(char)*2))){
printf("malloc error\n");
throwInternError();
}
data[0]=c;
data[1]='\0';
return data;
}
else
{
if((p = (char*)realloc(data,((strlen(data)+2)*sizeof(char))))){
data = p;
}
else{
printf("realloc error\n");
throwInternError();
}
data[strlen(data)+1] = '\0';
data[strlen(data)] = c;
return data;
}
}


This is how I use addDataChunk:

temp_char =getc(pFile);
temp_string=addDataChunk(temp_string,temp_char);


When I do these two lines:

printf("%s\n","Hello\nWor'ld\\\042");
printf("%s\n",temp_string);


I get this:

Hello
Wor'ld\"
Hello\nWor'ld\\\042


Do somebody know why the output is different?

Answer

Your texte file contains

Hello\nWor'ld\\042

Now if you read this file character by character with getc you will get the characters verbatim, that means you will get successively:

H, e, l, l,o,\,n, ..., \, \, \, 0, 4, 2.

On the other hand the string literal "Hello\nWor'ld\\\042" will be transformed by the compiler into:

H, e, l, l,o,\n, ..., \, ".

Actually \n will be translated into the ASCII character 10 (line feed), \\ will be translated into \ and \042 will be translated into the ASCII character whose value in octal is 042 that is ".

You should read about escape sequences.