mor*_*hio 1 c arrays static header
我使用了一个二维数组的字符,应该由C中的多个函数编写和读取.
这是我的阵列:
static char array[3][6];
Run Code Online (Sandbox Code Playgroud)
让我们说我有一个函数'Function()'来修改这个数组.如果函数在main中定义没有问题(数组被正确写入然后读取),但如果我想将我的函数放在另一个文件中,那么数组是正确写入的,但是当我在main中返回时是神奇地空了!这是我的代码.
main.c中
#include "support.h"
int main(int argc, char *argv[])
{
Function();
unsigned i, j;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 6; j++)
printf("[%c]", array[i][j]);
printf("\n");
}
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
support.h
static char array[3][6];
Run Code Online (Sandbox Code Playgroud)
support.c
void Function()
{
char hello[6];
hello[0] = 'H';
hello[1] = 'E';
hello[2] = 'L';
hello[3] = 'L';
hello[4] = 'O';
hello[5] = '\0';
strcpy(array[0], hello);
}
Run Code Online (Sandbox Code Playgroud)
没有编译错误也没有运行时错误.再一次,如果我尝试移动main.c中的所有内容都可以工作,如果我分成两个文件则不然(数组一旦从Function()返回就会正确,然后它被释放),怎么样有可能吗?
通过array在头文件中声明为静态,您可以为每个源文件提供包含support.h其自己的副本的文件.您需要将标题更改为
extern char array[3][6];
Run Code Online (Sandbox Code Playgroud)
并添加
char array[3][6];
Run Code Online (Sandbox Code Playgroud)
到一个源文件.