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: "Mike Harrold" <mharrold at cas dot org>, "Markus Virtanen" <Markus at colorplaza dot com>
- Subject: RE: What is the difference between char *str and char str[] ?
- From: "Tuukka Tikkanen" <tic0 at tic0 dot net>
- Date: Thu, 26 Apr 2001 14:58:20 +0300
- Cc: <gcc-bugs at gcc dot gnu dot org>
> -----Original Message-----
> Subject: 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.
>
> If you compile your code with -fwritable-strings, it will work
> as expected.
Still, not quite the same behaviour!
Assume you have these functions (and compile using -fwritable-strings to
make the latter "work"):
void fn1(int x)
{
char foo[] = "The number was not 1";
if(x==1) strcpy(foo,"The number was 1");
printf("%s\n",foo);
}
void fn2(int x)
{
char *foo = "The number was not 1";
if(x==1) strcpy(foo,"The number was 1");
printf("%s\n",foo);
}
and a main for them as well:
int main(void)
{
fn1(1);
fn1(0);
fn2(1);
fn2(0);
}
The output would be:
The number was 1
The number was not 1
The number was 1
The number was 1
Why? Because in fn1() the string foo is initialized every time to "The
number was not 1", but in fn2() all that is initialized is the pointer to a
string in fixed memory location, which the first call to fn2() changes.
Therefore you should not assume that -fwritable-strings would make using
char * and char[] equal. Although an array variable is converted to a
pointer by the compiler where necessary and you can use indexing to access
via a pointer, they are not the same thing at all.
Tuukka