2
char a[] = "hello";
char *p = "world";
p = &a[1]; /* no 1, valid */
p[1] = &a[1]; /* no 2, invalid*/
p[1] = *a; /*no 3, invalid*/
a= p /* no 4, invaild */

In C, I thought a[] and *p was the exactly the same thing.
But, as the no 1 and 4 shows I found that you can't assign it to array name like a, when you can assign it to p since it's a pointer.
Is this the only difference between declaring string array in two different ways?
Having said that, if you can assign it to the pointer, why no 2 and no 3 are invalid? Thank you.

dbush
  • 205,898
  • 23
  • 218
  • 273
raven39
  • 135
  • 1
  • 7

1 Answers1

3

Arrays and pointers are not the same thing. An array is a collection of identical objects, whereas a pointer points to one or more objecvts. Where the confusion comes in is that an array name, when used in an expression, will in most cases decay into a pointer to the first element. This means a and &a[0] evaluate to the same thing.

Looking at each case:

p = &a[1];

This is valid because a[1] is a char so &a[1] is a char *, which matches the type of p.

p[1] = &a[1];

Invalid, because p[1] has type char but &a[1] has type char *. Also invalid at run time because p points to a string constant which can't be modified.

p[1] = *a;

The syntax is valid because both p[1] and *a have type char. However, p points to a string constant which can't be modified so you end up with undefined behavior

a= p;

Invalid, because an array cannot be assigned to.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you. But Why is p[1] a string constant, when a[1] is not? – raven39 Apr 03 '19 at 03:05
  • 1
    [`char* x = "..."` is a constant string, but `char x[] = "..."` is not](https://stackoverflow.com/questions/9436781/c-string-array-initialization-is-this-mutable). – tadman Apr 03 '19 at 03:11
  • 2
    @JessicaKim `a` is an array which is initialized with a string constant. It's elements contain the same values as the string constant but it's not the same object. `p` on the other hand points to a string constant, so dereferencing `p` gives you an element of the string constant. – dbush Apr 03 '19 at 03:12