This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: What is the difference between char *str and char str[] ?


> 
> 
> I have a small test program that causes seg fault if 
> I define a string as: char *test = "some text";
> and pass that string to a function that manipulates it. 
> However if I define it as char test[] = "some string"; 
> everything works fine.
> 
> Again some detail I didn't learn at University?

Perhaps. The issue is that by default, gcc uses "4444 2222 7777 8888"
as a const string. The best way to understand it is that:

	char *test = "4444 2222 7777 8888";

should be

	const char *test = "4444 2222 7777 8888";

If you compile your code with -fwritable-strings, it will work
as expected.

/Mike


> 
> ------- 8< ----------------------
> #include <stdio.h>
> 
> /* Taken from K&R 2nd ed. p 47 */
> 
> void squeeze(char *s, char c)
> 
> {
> 
>     int i=0, j=0;
> 
> 
>     for (i=0,j=0; s[i] != '\0'; i++) 
> 
>         if (s[i] != c) 
> 
>             s[j++] = s[i];
> 
>     }
> 
>     s[j] = '\0'; 
> 
> }
> 
> int main(void)
> 
> {
> 
>     char *test = "4444 2222 7777 8888";
> 
> 
>     squeeze(test, ' ');
> 
> 
>     printf("New string: %s\n", test);
> 
> 
>     return 0;
> 
> }
> 
> 
> 
> 
> 


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]