Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

Pointers and arrays between files..

Please go thru the fn below and tell me how to explain the reason why the pointer notation does not work with external arrays.


int a[10] = { 1,2,3,4};


extern int *a;
int b[10];
#include <stdio.h>

void Print()
  int *c = b;

  printf("%d\n", a[0]); //does not print
  printf("%d\n", (&a)[0]); //prints
  printf("%d\n", c[0]); //prints
  • 2
1 Solution
If I recall correctly
int *a;
int a[10];
are different variable declarations according to the linker - therefor it will not "link" them as the same variable.

You should use
extern int a[];

Kent OlsenData Warehouse Architect / DBACommented:

Within file1, the declaration 'int a[10]' reserves ten integers.  The nature of an integer array is such that you actually put a 1 into element 0, 2 into element 1, etc.

Withing file2, the declaration 'extern int *a' doesn't reserved space.  It tells the compiler that the "already defined symbol 'a'" contains a pointer to an integer.  Where you stored a 1 in element 0, this declaration treats the contents of 'a' as a pointer to an integer.  If a pointer and an int are the same size, you're using the value 1 as an address.  It implies that the array is created by:

  int *a = (int *)malloc (10 * sizeof (int));

Writing the declaration as 'extern int a[]' tells the compiler that the "already defined symbol 'a'" is an array of consecutive integers.

This is quite subtle -- I missed it the first time that I looked at it.  If this had been posted as a quiz, without stating that the code didn't work, I'd have flunked.  :(

nagubalaAuthor Commented:
Thanks! Thats a good way to put it.
This also points out that C should never have a relaxed syntax that array name and a pointer are the same. If they have made it mandatory that only by applying the & operator one can get the address of an array, then this problem would never arise and that rule will universally be applicable. That will also invalidate the extern int *a declaration.
Kent OlsenData Warehouse Architect / DBACommented:

The standard is much more stingent in C++, which was part of the intent when C++ was developed.

Be aware that as you transition the data type from int to char and finally string (char*) that the behavior may fool you, again.

Strings are already pointers to objects so you'll often see '*' and '[]' used on strings just like you tried to use them on integers.


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now