C语言realloc函数使用疑问:指针解引用差异解析请求
疑问解答
核心疑问拆解
针对语句x = realloc(x, (*x+1) * sizeof(int));的两个问题:
1. 为何realloc第一个参数是x,不用解引用?
realloc的第一个参数要求传入已分配内存的指针地址,用来指定要调整大小的目标内存块。这里的x是int*类型的指针,本身就存储着内存块的起始地址,直接传入完全符合函数参数要求。如果对x解引用(*x),得到的是一个int数值,这不是realloc需要的指针类型,会直接触发编译错误。
2. 为何第二个参数里要用(*x+1)?
这段代码采用了特殊的动态数组设计:把内存块的第一个int位置用来存储元素的总数量,后续空间才用来存放实际元素。
- 一开始
x = malloc(sizeof(int))只分配了1个int的空间,用来接收用户输入的元素个数(通过scanf("%d", x)把输入值存在x指向的内存里,此时*x就是用户输入的元素数量)。 - 扩容时,需要的总空间是「元素数量+1」个int:1个位置存数量,剩下的
*x个位置存实际元素。(*x+1)*sizeof(int)就是计算出需要的总字节数。
3. 这是不是指向指针的指针?
不是。代码里的x是普通的int*(指向int的指针),只是用法上把它指向的第一个int当作元素计数器来用,本质还是单级指针。
附原代码
#include <stdio.h> #include <stdlib.h> #include <assert.h> int* cut(int* x, int n); int main() { int *x= NULL,n; x = malloc(sizeof(int)); printf("Amount of elements: "); scanf("%d", x); x = realloc(x, (*x+1) * sizeof(int)); assert(x != NULL);// allocate memory and ensure that this was successful for (int i = 1; i <= *x; i++) { printf("%d Element: ", i); scanf("%d", x+i); } printf("pper barrier: "); scanf("%d", &n); x = cut(x,n); for (int i = 1; i <= *x; i++) { printf("%d ", *(x+i)); } printf("\n"); free(x); } int* cut(int *x, int n) { int a = 1; for (int i = 1; i <= *x; i++) { if(*(x+i) < n) { *(x+a) = *(x+i); a++; } } *x = a-1; x = realloc(x, (a+1) * sizeof(int)); return x; }
内容的提问来源于stack exchange,提问作者kilston
相关产品推荐
相关产品推荐

