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.

7
  • Hint: What type is p[1]? Commented Apr 3, 2019 at 1:59
  • Another hint: a[] and *p are not exactly same thing. try sizeof a and sizeof p. Commented Apr 3, 2019 at 2:04
  • @niry I got 6 and 8, when I did sizeof a and p. can you explain why? Commented Apr 3, 2019 at 3:02
  • @tadman It's a char. But can you explain it why is it a constant? Commented Apr 3, 2019 at 3:02
  • 1
    @JessicaKim sure! sizeof(a) is 6 which it is the size of the array "hello" (5) plus null char '\0' (1). sizeof(p) is 8 which is the size of a pointer on a 64bit architecture (8 bytes * 8 bits = 64 bits) Commented Apr 3, 2019 at 3:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. But Why is p[1] a string constant, when a[1] is not?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.