gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:41:38 25 4
gpt4 key购买 nike

我在这里看了几个例子,但我仍然对此一头雾水。我的头文件中有一个 extern int *sharedarray[]。我在我的三个 .c 文件中将其定义为 int *sharedarray[]。在我的第一个 .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

最佳答案

请执行以下操作....

标题.h

extern int* array;

文件1.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;

文件2.c

#include "header.h"

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

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

希望这能帮助您解决问题,谢谢

PS - 请仅将上面的代码用作示例 - 而且我在工作中很快就写了这个 - 所以请原谅任何错字或错误。

关于c - 如何在 C 中的程序之间共享动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com