我在理解C语言中的realloc函数时遇到了问题

tpgth1q7  于 2022-12-03  发布在  其他
关注(0)|答案(3)|浏览(121)

代码如下:

#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;
}

代码运行良好,但是我不理解x = realloc(x, (*x+1) * sizeof(int));行。此外,我不明白为什么第一个xno *,而第二个(*x+1)有一个。这意味着指针的指针吗?
我想这只是意味着数组malloc变大了一个值,但是我不确定,仍然有点困惑这到底是什么意思,有人能帮我澄清一下我的误解吗?

nbnkbykc

nbnkbykc1#

x = realloc(x, (*x+1) * sizeof(int));

Let's start with this part:

x = realloc(x, ...

The code is calling realloc and passing as the first parameter whatever x points to and storing the result in x . That means that the block currently pointed to by x will be resized and the result stored in x . So x will point to a resized version of whatever x pointed to before.
The (x + 1) * sizeof(int) is the size of the block. Let's start with the right side, * sizeof(int) . That means enough space to store some number of int s. How many int s? *x + 1 of them.
So this means to change x to point to a resized version of the block x already pointed to, resizing the block to hold one more integer than the value of the integer x points to.

blmhpbnm

blmhpbnm2#

scanf("%d", x);

这会将位址x处的整数设定为使用者输入的值。例如,如果使用者输入3,这一行的作用就相当于*x = 3;

x = realloc(x, (*x+1) * sizeof(int));

*x正在解引用x,而不是指向x的指针(即&x)。因此,它是用户键入的值。因此,这行代码使x指向一个N+1个元素的数组,其中N是用户键入的值。(假设内存分配成功。)
后来,在cut中,

*x = a-1;
x = realloc(x, (a+1) * sizeof(int));

这两行再次保持不变,即数组的第一个元素是后面的元素数。

u91tlkcl

u91tlkcl3#

我不明白这条线
x是一个int**x解引用x(这样就可以得到用户在前面的scanf("%d", x);中输入的值)。因此,(*x + 1)表示,“用户输入的值加一”。将其与int的大小相乘。reallocx参数是您想要增加已配置内存的先前配置指标。传回的指标(可能与先前的x相同,也可能是新的值)接着会指派给x
另外,我不明白为什么第一个x没有*,而第二个(*x+1)有一个。这意味着指针的指针吗?
x = ...表示“为x赋值“。realloc返回一个void*,它可以隐式转换为任何指针类型,如int*,而x是一个int*
(*x + 1)中,*用于取消引用x,即获取x所指向的int的值。

相关问题