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 ?
我在这里看了几个例子,我仍然对此感到满意。我的头文件中有一个extern int * sharedarray []。我在我的三个.c文件中将其定义为int * sharedarray []。在我的第一个.c文件中,我分配了malloc需要多少内存。它必须在那时动态分配。之后我设置了值。为了测试的目的,我只是将它们递增1.然后,另一个.c文件,我去打印数组。什么是0,1,2,3已成为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?
我完全不知道这里发生了什么。我确信这很简单,但它已经阻止了我超过4个小时了。有谁知道我应该怎么做?
header.h
header.h
extern int *array[];
file1.c
在file1.c
int *array[];
file2.c
file2.c中
int *array[];
My make files uses:
我的make文件使用:
file1: $(proxy_obj) file2.o, header.o
1 个解决方案
#1
2
Please do the following ....
请执行以下操作....
header.h
header.h
extern int* array;
file1.c
在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
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.
从读取您的请求,您需要一组int,并能够在两个源文件之间使用它们。
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.
PS - 请仅使用上面的代码作为示例 - 我也在工作中快速写了这个 - 所以请原谅任何拼写错误或错误。
#1
2
Please do the following ....
请执行以下操作....
header.h
header.h
extern int* array;
file1.c
在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
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.
从读取您的请求,您需要一组int,并能够在两个源文件之间使用它们。
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.
PS - 请仅使用上面的代码作为示例 - 我也在工作中快速写了这个 - 所以请原谅任何拼写错误或错误。