-3

I am new to C language. I have a confusion regarding pointers in C.

Here is a short program:

void main() {
    int *array_ptr,big_array[20];
    array_ptr=big_array;
}

Here when we equated pointer to the name of array then C will assign the address of first element of array to the pointer as it know that array_ptr is a pointer and will store an address. Whereas in this case,

 void main() {
     int i, *x;
     x = i;
 }

Here, it will throw an error. In this, we have to use &i to assign it to pointer x. why we need to use & in case of integers/floats etc and don't need to use it in case of array?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
jigglypuff
  • 309
  • 1
  • 2
  • 8
  • 2
    The main function does not return `void`, it always returns `int`. As far as your question, [arrays decay to pointers](http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c). Any C book should have explained this. – Cody Gray - on strike Aug 30 '14 at 03:54
  • +1. I don't know why this question receives **four** downvotes. (because of formatting?) – ikh Aug 30 '14 at 03:55
  • 3
    @ikh Perhaps because "This question does not show any research effort" – Cody Gray - on strike Aug 30 '14 at 03:57
  • 1
    @chipChocolate That is a good edit, but in the future, please use inline code formatting only for *code*. The name of the language (C) is not code. – Cody Gray - on strike Aug 30 '14 at 04:13

1 Answers1

1

The difference is that when an array name is specified without a subscript, C substitutes in a pointer to the first element of the array. Therefore, if you have an array of ints named array, then:

array === &array[0]

When used to assign to a pointer type. The difference is simply in the types -- int (and all of the primitive types) are treated differently than arrays, which are collections of types. So pointers work differently too, and it's simply a matter of knowing how the compiler handles them.

jackarms
  • 1,343
  • 7
  • 14
  • i got it now.thanks jackarms. – jigglypuff Aug 30 '14 at 04:06
  • 2
    This is inaccurate. An expression of array type (including an array name) is implicitly converted to a pointer to the array's first element in most but not all contexts. This conversion specifically happens for the indexing operator, which actually requires a pointer and an integer as its operands. One of the exceptions is the `sizeof` operator; `sizeof array` yields the size of the array, not the size of a pointer (which shows that arrays don't *always* decay to pointers). – Keith Thompson Aug 30 '14 at 04:29