This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: What is the difference between char *str and char str[] ?
- To: Markus at colorplaza dot com (Markus Virtanen)
- Subject: Re: What is the difference between char *str and char str[] ?
- From: Mike Harrold <mharrold at cas dot org>
- Date: Wed, 25 Apr 2001 11:08:45 -0400 (EDT)
- Cc: gcc-bugs at gcc dot gnu dot org
>
>
> 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;
>
> }
>
>
>
>
>