【发布时间】:2018-01-09 18:18:14
【问题描述】:
如果我有int **array 并想在其中放置一系列数字(我不知道它的大小),以5 3 4 0 或9 1 5 8 3 0 为例。据我所知,我应该使用malloc
所以我做了这样的事情
int **array;
int n = 1, inp = 0;
while(n){ // scan till the input is 0
scanf("%d", &n);
array = (int**)malloc(sizeof(int*)*(inp+1)); //since inp start at 0
array[inp] = &n; //is this even correct?
inp++;
}
我的第一个问题是:这个方法(循环)会升级/扩展array 的大小还是我在做什么浪费内存?
第二个问题是如何打印/编辑这个array 的值?
编辑:
根据您的回答,我得出以下结论。
int **array;
int n = 1, inp = 0;
array = (int**)malloc(sizeof(int*));
while(n){
scanf("%d", &n);
realloc( array, sizeof((int*)(inp+1)));
array[inp] = n;
inp++;
}
这是正确的做法吗?
注意*我知道它不一定是指针的指针,但我需要它稍后用于其他东西。
【问题讨论】:
-
这个数组[inp] = &n;没有意义,因为数组的所有元素都将具有相同的值:变量 n 的地址。
-
为什么是双指针?你不只是想要一个一维整数数组吗?不,循环内的 malloc 是个坏主意。 realloc 更好。
-
不要为此使用
malloc- 这都是错误的。使用realloc -
... 和一个初始值为 NULL 的指针。
-
@LeeDanielCrocker 我稍后会添加更多的一维数组。