【发布时间】:2015-02-03 18:25:36
【问题描述】:
我有一个指向指针(“路径”)的指针,我想重新分配每个指针(每个“路径”)。但我遇到了崩溃。一般来说,我试图找到一个数字的所有可能的幂,一个可以计算一定数量的操作(例如,对于两个操作,我们可以获得三和四的幂(一个操作用于数字的平方,然后另一个操作用于幂三或四个))。我想出了如何在纸上做到这一点,现在我正在尝试在代码中实现它。这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
【问题讨论】:
-
您使用临时指针来防止覆盖以前的
paths[j],但您仍然永远不会检查realloc是否返回NULL。 -
现在我检查了它,但它没有帮助,程序在重新分配行崩溃并且没有提前进行返回值检查,也许我在重新分配时做错了
-
另外,从
malloc/realloc中删除演员表,它不会修复您的程序,但它会使其更具可读性。 -
您正在使用
path和paths并为它们所代表的指针分配内存,但从不为要写入的数据分配内存(空间)。 (即类似for(i=0;i<n;i++)( path[i] = malloc(...);} -
我在 // 路径初始化之前做了类似的事情,我猜它可以工作,因为后来我通过调用 print_path(paths[i], npath); 打印所有路径;
标签: c pointers crash allocation pointer-to-pointer