我尝试使用malloc
首先为数组分配一些空间,然后使用realloc
来扩展数组。该程序可以编译,但当我运行该程序时,我在终端中得到一些奇怪的内存打印。终端会显示如下内容:========内存映射=========
,然后是一堆数字和其他内容。
在我的程序中,我使用 malloc 如下:
struct station *addStation(struct station *graph, struct station newStation){
graph = realloc(graph, sizeof(graph)+sizeof(struct station));
// Count the rows of graph[] here and add newStation to the end.
}
int main(){
struct station *graph;
graph = malloc(145*sizeof(struct station));
graph = loadStations();
newStation = graph[27];
graph = addStation(graph, newStation);
}
我用错了吗?
最佳答案
您正在覆盖内存所在的指针:
graph = malloc(145*sizeof(struct station));
graph = loadStations(); // malloc'd memory is lost here
如果您想向内存添加一些数据,则需要将其作为指针传递:
loadStations(graph);
此外,您的 sizeof(graph)+sizeof(struct station)
仅将数据保留到 1 个指针和 1 个站,这不是您想要的。您需要传递现有的尺寸信息:
struct station * addStation(struct station * graph, size_t * count, struct station newStation){
size_t newCount = *count + 1;
graph = realloc(graph, newCount * sizeof(struct station));
if(!graph)
return 0;
*count = newCount;
// Copy new station here
return graph;
}
并在main中调用:
temp = addStation(graph, &graphCount, newStation);
if(temp)
graph = temp;
关于c - 使用 malloc、C 在终端中打印奇怪的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19022515/