Is an array name a pointer?

Viewed 95198

Is an array's name a pointer in C? If not, what is the difference between an array's name and a pointer variable?

8 Answers

The following example provides a concrete difference between an array name and a pointer. Let say that you want to represent a 1D line with some given maximum dimension, you could do it either with an array or a pointer:

typedef struct {
   int length;
   int line_as_array[1000];
   int* line_as_pointer;
} Line;

Now let's look at the behavior of the following code:


void do_something_with_line(Line line) {
   line.line_as_pointer[0] = 0;
   line.line_as_array[0] = 0;
}

void main() {
   Line my_line;
   my_line.length = 20;
   my_line.line_as_pointer = (int*) calloc(my_line.length, sizeof(int));

   my_line.line_as_pointer[0] = 10;
   my_line.line_as_array[0] = 10;

   do_something_with_line(my_line);

   printf("%d %d\n", my_line.line_as_pointer[0], my_line.line_as_array[0]);
};

This code will output:

0 10

That is because in the function call to do_something_with_line the object was copied so:

  1. The pointer line_as_pointer still contains the same address it was pointing to
  2. The array line_as_array was copied to a new address which does not outlive the scope of the function

So while arrays are not given by values when you directly input them to functions, when you encapsulate them in structs they are given by value (i.e. copied) which outlines here a major difference in behavior compared to the implementation using pointers.

Related