Andrey Liberty Andrey Liberty - 3 months ago 8
C Question

dynamically allocated string populated with characters results in empty string C

int main(){
char *c=(char*)malloc(4*sizeof(char));
*c='a';
c++;
*c='b';
c++;
*c='c';
c++;
*c='\0';
printf("%s",c);
return 0;
}


With this code I can print every single character (e.g.
printf("%c",*(--c));
), but when I try to print the whole string using
printf("%s",c);
the program prints nothing! Why is this happening ?

Jay Jay
Answer

The pointer has been moved. So it is now pointing to the last character which is a "\0". So, nothing is printed. Preserve the pointer in another variable and try to print using that. It will then print correctly.

Try like below:

int main()
{
    char *p;
    char *c=(char*)malloc(4*sizeof(char));
    p = c;
    *c='a';
    c++;
    *c='b';
    c++;
    *c='c';
    c++;
    *c='\0';
    printf("%s",p);
    free(p);
    return 0;
}
Comments