Home > Enterprise >  Making two arrays occupy same memory region in C language
Making two arrays occupy same memory region in C language

Time:11-15

Arrays in C are actually constant pointers. The pointer to the first element of an array is a constant. Therefore it seems impossible to assign an address value to the array pointer.

But in some situations it might be useful to have two arrays point to the same location in memory.

So how can I make two arrays point to the same location in such fashion :

int a[10];
int b[10];

a = b; // Not possible

What is below seems to be a valid solution. But, are there alternatives?

int *a;
int *b;
int c[10];

a = c;  // If you change the value "a" points to
b = c;  // it will be observed on "b"

a[2] = 5;
printf("Output is %d", b[2]);

>> Output is 5

CodePudding user response:

Arrays behave like pointers to their first element, but you can't reassign them:

int a[] = { 1, 2 };
int b[] = { 3, 4 };
b = a; // compilation error: b is constant

The reason is their address, being known at compile time, is stored in a read-only segment of the program, and writing in a read-only segment would be a segmentation fault.

A pointer is a type which contains an address, it can be assigned at runtime. If you don't know at compile-time how much memory you need, you can ask some to your system with dynamic allocation:

int * integers = malloc(sizeof(int) * 3); // dynamic array of size 3
// or 
int * integers = malloc(sizeof(* integers) * 3);

If you want 2 arrays to point to the same memory:

char * interval1 = malloc(sizeof(char) * 2); // sizeof() useless here, char is defined as 1 byte 
interval1[0] = 'A'; // equivalent to *(p   0) = 'A'
interval1[1] = 'Z';  // equivalent to *(p   1) = 'Z'

char * interval2 = interval1;

But the interest is rather limited if both variables are in the same function.

I didn't add checks, but you should always check for NULL after allocation, and free() when you don't need the memory anymore.

TDLR: if you need to reassign an address, don't use array-type, but pointer-type, it's made to be dynamic.

  • Related