2

So, in C, this perfectly works:

int myArray[] = {1, 2, 3};

why does the following give me a runtime error when accessing an element?

int * myArray2 = {1, 2, 3};
myArray2[0];

when myArray2[0] basically means *myArray2, which does also not work?

Daniel D.
  • 178
  • 2
  • 15
  • 1
    `int * myArray2 = {1, 2, 3};` is an error; if you don't see an error message then please adjust your compiler settings. Runtime behaviour is meaningless given that the code should be a compilation error in the first place – M.M Mar 01 '18 at 01:04
  • so {1, ...} is only possible when explicitly declaring the variable as an array? – Daniel D. Mar 01 '18 at 01:05
  • Arrays and structs can have multiple initializers (one for each element), the only possible initializer for a pointer is the address of a memory location (or a null) – M.M Mar 01 '18 at 01:06
  • 1
    Pointers are not arrays, and arrays are not pointers. – ad absurdum Mar 01 '18 at 01:07

2 Answers2

6

I think that the fundamental difference is that declaring an array implicitly allocates memory, while declaring a pointer does not.

int myArray[3]; declares an array and allocates enough memory for 3 int values.

int myArray[] = {1,2,3}; is a little syntactic sugar that lets the size of the array be determined by the initialization values. The end result, in terms of memory allocation, is the same as the previous example.

int *myArray; declares a pointer to an int value. It does not allocate any memory for the storage of the int value.

int *myArray = {1,2,3}; is not supported syntax as far as I know. I would expect you would get a compiler error for this. (But I haven't done actual C coding in years.) Even if the compiler lets it through, the assignment fails because there is no memory allocated to store the values.

While you can deference a pointer variable using array syntax, this will only work if you have allocated memory and assigned its address to the pointer.

Dave Costa
  • 47,262
  • 8
  • 56
  • 72
0

Pointer and Array are different. One difference between them is the subject of your question. When you define an array with the specified size, you have enough memory to initialize it.

However, in the pointer, you should allocate the memory to initialize it. Hence, you should first allocate the memory using a function like malloc and point the pointer to the allocated memory. Therefore, the problem with the second code is you want to access the part of the memory which is not allocated. You can correct it likes the following:

int *myarray2 = malloc(3*sizeof(int));
myarray2[0] = 1;
myarray2[1] = 2;
myarray2[2] = 3;
OmG
  • 18,337
  • 10
  • 57
  • 90