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[] ?


> -----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


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