这是我要创建结构 vector 的程序的一部分
typedef struct {
char nome[501];
int qtd;
int linha;
int coluna;
} tPeca;
tPeca* criarPecas(FILE *pFile, int tam) {
int i;
tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca));
if (pecaJogo == NULL)
return NULL;
for (i = 1; i <= tam; i++) {
fscanf (pFile, "%[^;]", pecaJogo[i].nome);
fscanf (pFile, "%d", pecaJogo[i].qtd);
fscanf (pFile, "%d", pecaJogo[i].linha);
fscanf (pFile, "%d\n", pecaJogo[i].coluna);
}
return pecaJogo;
}
如果我改变
tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca));
if (pecaJogo == NULL)
return NULL;
到
tPeca pecaJogo[tam];
它工作正常但给出一些警告
[Warning] function returns address of local variable [-Wreturn-local-addr]
最佳答案
该消息明确指出:使用 malloc
,您分配的空间在创建它的函数 criarPecas
返回后仍然存在。您的更改分配的空间会在函数返回时被回收,因此可以自由用于其他事情,因此可以被程序的另一部分覆盖。
如果您的程序真的“运行良好”,您可能只是走运了。
关于C语言,vector of struct,漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835870/