我对 malloc 和 realloc 的理解出了什么问题?
What am I getting wrong on malloc and realloc understanding?
我试图制作一个数组,它可以在程序 运行 时调整大小。我已经了解了 malloc 和 realloc 函数,但似乎我显然弄错了。这是我编写的函数,它根据循环生成的周期数创建一个数组。
int* flexibleArray() {
int *arrayFlex = NULL;
int number=0, cnt=0;
while (number!=-1) {
printf("\nInsert the variable: ");
scanf("%d", &number);
if (number==-1){
break;
}
cnt+=1;
arrayFlex = realloc(arrayFlex, cnt * sizeof(int));
arrayFlex[cnt-1] = number;
}
return arrayFlex;
}
我试图阅读我在互联网上找到的关于它的文档,我无法在重新分配后检索新数组。
int *array;
array = flexibleArray();
int arraySize = (sizeof(array))/(sizeof(int));
for(int i=0; i<arraySize; i++) {
printf("%d ", array[i]);
}
基本上这是我测试函数的地方,看它是否能正常工作。
我是 C 的新手,对不起大家。
谢谢
应该这样做。
int* flexibleArray() {
int *arrayFlex = NULL; // needs to be a pointer
int number=0, cnt=0;
while (number!=-1) {
printf("\nInsert the variable: ");
scanf("%d", &number);
if (number==-1){
break;
}
cnt+=1;
arrayFlex = realloc(arrayFlex, cnt * sizeof(int));
arrayFlex[cnt-1] = number;
}
return arrayFlex;
}
编辑:修正错别字。
我试图制作一个数组,它可以在程序 运行 时调整大小。我已经了解了 malloc 和 realloc 函数,但似乎我显然弄错了。这是我编写的函数,它根据循环生成的周期数创建一个数组。
int* flexibleArray() {
int *arrayFlex = NULL;
int number=0, cnt=0;
while (number!=-1) {
printf("\nInsert the variable: ");
scanf("%d", &number);
if (number==-1){
break;
}
cnt+=1;
arrayFlex = realloc(arrayFlex, cnt * sizeof(int));
arrayFlex[cnt-1] = number;
}
return arrayFlex;
}
我试图阅读我在互联网上找到的关于它的文档,我无法在重新分配后检索新数组。
int *array;
array = flexibleArray();
int arraySize = (sizeof(array))/(sizeof(int));
for(int i=0; i<arraySize; i++) {
printf("%d ", array[i]);
}
基本上这是我测试函数的地方,看它是否能正常工作。
我是 C 的新手,对不起大家。 谢谢
应该这样做。
int* flexibleArray() {
int *arrayFlex = NULL; // needs to be a pointer
int number=0, cnt=0;
while (number!=-1) {
printf("\nInsert the variable: ");
scanf("%d", &number);
if (number==-1){
break;
}
cnt+=1;
arrayFlex = realloc(arrayFlex, cnt * sizeof(int));
arrayFlex[cnt-1] = number;
}
return arrayFlex;
}
编辑:修正错别字。