Search code examples
carraysdynamicextern

How do I share a dynamically allocated array between programs in C


I have looked at several examples here and I am still coming up empty with this. I have an extern int *sharedarray[] in my header file. I define it as int *sharedarray[] in my three .c files. In my first .c file I allocate how much memory it is going to need with malloc. It must be dynamically allocated at that point. After that I set the values. For the purpose of testing I am just incrementing them by 1. Then, another .c file, I go to print the array. What was 0,1,2,3 has become 0,3,2,2 ?

I am at a total loss for what is going on here. I am sure that this is something simple, but it has been blocking me for over 4 hours now. Does anyone know what I should do?

header.h

extern int *array[];

file1.c

int *array[];

file2.c

int *array[];

My make files uses:

file1: $(proxy_obj) file2.o, header.o

Solution

  • Please do the following ....

    header.h

    extern int* array;
    

    file1.c

    // ... in code
    // declared globally  
    int* array;
    
    // in your function...
    // numInts contain the number of ints to allocate...
    array = (int*)malloc( numInts, sizeof( int ));
    
    // set the values...
    array[ 0 ] = 0; 
    array[ 1 ] = 1; 
    array[ 2 ] = 2; 
    

    file2.c

    #include "header.h"
    
    //... in your function, print out values
    printf( "Values are %d,%d,%d\n", array[ 0 ], array[ 1 ], array[ 2 ] );
    

    From reading your request, you want an array of ints and to be able to use them between two source files.

    Hope this helps you sort out your problem, thanks

    PS - Please use the above code as example only - also I have written this quickly at work - so forgive any typo's or errors.