Help me in solving 2 questions on pointers:
1)Please tell me why do I get ‘segmentation fault’ when I run following snippet
main()
{
char *str1 = "united";
char *str2 ="front";
char *str3;
str3 = strcat(str1,str2);
printf("\n%s",str3);
}
2)Why don’t I get output in following code:
main()
{
char str[10] = {0,0,0,0,0,0,0,0,0,0};
char *s;
int i;
s = str;
for(i=0 ; i<=9;i++)
{
if(*s)
printf("%c",*s);
s++;
}
}
Thank u.
You should review how strcat works. It will attempt to rewrite the memory at the end of your
str1pointer, and then return the destination pointer back to you. The compiler only allocated enough memory instr1to hold “united\0” (7 chars), which you are trying to fill with “unitedfront\0” (12 chars).str1is pointing to only 7 allocated characters, so there’s no room for the concatenation to take place.*swill dereferences, effectively giving you the first character in the array. That’s 0, which will evaluate to false.