-1

I am trying to understand why an array variable cannot point anywhere else?

Sample code:

 char s[] = "How big is it";
 const char *t = s;

This is the code,I create a sample array s[] and assign it a value "How big is it", now I create a character pointer array and assign it the value of s's address.

Now when I say something like this,the complier throws me an error:

 s=t;      ----> compiler error

Why is that? Is it because the string literal reference would get lost?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Govardhan Murali
  • 91
  • 1
  • 1
  • 8
  • Read any good book about C programming. You cannot assign into an array (intuitively, because the `sizeof` of `s` is much bigger than the `sizeof` any pointer, which is always 8 on my machine). Ask yourself how the compiler should translate what you are trying to write! – Basile Starynkevitch Jan 10 '16 at 08:14
  • 2
    "now I create a character pointer array" You don't. You create a character pointer. "why is that?? Is it because the string literal reference would get lost??" No, that's because you are not allowed to assign to an array. – n. m. could be an AI Jan 10 '16 at 08:16
  • 1
    It is a language design decision: arrays are not assignable. Also, arrays don't *point* to data, they *are* the data. – juanchopanza Jan 10 '16 at 08:35
  • Possible duplicate of [Is an array name a pointer in C?](http://stackoverflow.com/questions/1641957/is-an-array-name-a-pointer-in-c) – Bo Persson Jan 10 '16 at 08:40

1 Answers1

0

= sign has two different meanings in C: initialization and assignment.

When you write char s[]="How big is it";, you initialize a new array with the characters of the string literal including the terminating null.

And the language simply does not allow assignment to an array. It would not make sense anyway because once defined, an array identify a memory location. You can then only assign to array elements or use functions that do that under the hood (memxx, strxx).

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252