我发布此示例代码以解释我的问题。我试图在函数之间传递一个指向整数的指针。如果你编译&运行此代码,您将看到出现奇怪的数字,我无法理解。我认为realloc()
的使用很糟糕。如果有人可以提示或者可能会将我重定向到类似于此的一些问题,我将不胜感激。我搜索这个问题,但找不到类似的东西。
#include <stdio.h>
#include <stdlib.h>
void myFunction(int **output);
int main(){
int *indices;
myFunction(&indices);
printf("{");
for(int i=0;i<10;i++){//suppose also for some mysterious reasons that I know min_size in the main
printf("%i,", indices[i]);
}
printf("}\n");
return 0;
}
void myFunction(int **output){
int size = 130;//allocating big amount of space
int* indices = malloc(sizeof(int)*size);
//...start doing mysterious stuffs....
int min_size = 10;
for(int i=0;i<min_size;i++){
indices[i] = i;//just for saving something
}
//...end doing mysterious stuffs...
//now for some reasons I know I need only min_size elements and all other are wasting space so I reallocate
indices = realloc(indices,min_size);//resizing in order to save space
*output = indices;
}
答案 0 :(得分:2)
您使用的是realloc错误。重新分配范围的大小必须为
min_size * sizeof( int )
你在这里
#include <stdio.h>
#include <stdlib.h>
void myFunction(int **output);
int main( void )
{
int *indices;
myFunction(&indices);
printf("{");
for(int i=0;i<10;i++){//suppose also for some mysterious reasons that I know min_size in the main
printf("%i,", indices[i]);
}
printf("}\n");
return 0;
}
void myFunction(int **output){
int size = 130;//allocating big amount of space
int* indices = malloc(sizeof(int)*size);
*output = indices;
// ^^^^^^^^^^^^^^^
//...start doing mysterious stuffs....
int min_size = 10;
for(int i=0;i<min_size;i++){
indices[i] = i;//just for saving something
}
//...end doing mysterious stuffs...
//now for some reasons I know I need only min_size elements and all other are wasting space so I reallocate
indices = realloc(indices, min_size * sizeof( int ) );//resizing in order to save space
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if ( indices ) *output = indices;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
程序输出
{0,1,2,3,4,5,6,7,8,9,}