define as pointer, references as array

Since 2002, I’ve recently began again to make code in C language by creating Pebble SmartWatch application. Although the last  image of the language is actually “too verbose to achieve” what I imagined, but now I don’t feel that much like the time when I had struggled. Probably because other programming languages have helped me, I guess. It fells like even fresh to me.

 

When the source code is getting big, we tend to make modules in general. In C language, we use extern declaration and refer from other source files.  In this case, we have to be careful not to re-declare as pointer the variable that is already defined as array. They, array and pointer, seem alike to each other but of course are not.

 

As we already know that the name of array is address itself and non-modifiable L-value that is fixed in compile time. Contrast to this fact, the name of pointer is its address of variable itself, its value is modifiable L-value that can be known only in compile time.  To get the actual value of pointer, it requires one more operation than array.

The point is that it will definitely cause errors if we re-declare some array variable as pointer and use it as array.

 

main.c


// main.c
extern void doSomething(void);

char name[] = "A.J";  //declare as array of char

int main(void) {
  doSomething();
  return 0;
}

other.c


// other.c
extern char *name;    //re-declare as pointer

void doSomething(void) {
  printf("name[1] = %c\n", name[1]);
}

 

Let us suppose to declare variable as array: char name[] = "A.J";

If we try to get the value of second item of array, we use this expression: name[1]

This expression means:

  • The name of name  is address and char is its type.
  • so we can get the value . from the location of the address of name + 1 byte
  • the value of  name[1] is NOT address but ASCII value .

But if we re-declare name as pointer, extern char *name; in other source files, and try to use name as if it is array(i.e name[1]),  things different.

  • Since the variable name is re-declared as pointer, compiler expects the name contains address value. But actually its value is simply ASCII value (in this case, .)
  • name + 1 causes error,  because pointer operation can not be performed.

 

$ gcc -o t main.c other.c
$ ./t
[1]    58885 segmentation fault  ./t

 

In short, do NOT re-declare (by extern declaration) primitive array variable as pointer. That’s it.