如何在C中的程序之间共享动态分配的数组

时间:2015-07-08 05:45:38

标签: c arrays dynamic extern

我在这里看过几个例子,我仍然对此感到满意。我的头文件中有一个extern int *sharedarray[]。我在我的三个int *sharedarray[]文件中将其定义为.c。在我的第一个.c文件中,我使用malloc分配了需要多少内存。必须在该点动态分配。之后我设置了值。出于测试的目的,我只是将它们递增1.然后,另一个.c文件,我转到print数组。什么是0,1,2,3已成为0,3,2,2?

我完全不知道这里发生了什么。我确信这很简单,但它已经阻止了我超过4个小时了。有谁知道我应该做什么?

header.h

extern int *array[];

file1.c中

int *array[];

file2.c中

int *array[];

我的make文件使用:

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

1 个答案:

答案 0 :(得分:2)

请执行以下操作....

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 ] );

通过阅读您的请求,您需要一组int,并且能够在两个源文件之间使用它们。

希望这可以帮助您解决问题, 感谢

PS - 请仅使用上面的代码作为示例 - 我也在工作中快速写了这个 - 所以请原谅任何拼写错误或错误。

相关问题