使用C中的动态数组与&*和[]()混淆

use*_*566 -1 c arrays pointers

我在C中有一个代码,其中包含以下行:

int i;
int *serie = malloc(sizeof(int)); 

    for (i = 0; i <= 20; i++){
        serie=rand(); 
        printf("%d ",&serie[i]);/* *serie */
    }
Run Code Online (Sandbox Code Playgroud)

它确实有用,但我想知道为什么,对于malloc,我相信我正在创建一个名为serie的动态数组或指针,到目前为止,我的知识是:

& returns the address
* returns the content of the adress
Run Code Online (Sandbox Code Playgroud)

使用固定数组[]和指针()

通过测试&serie[i]似乎工作,但它不*serie(i)还是*serie[i]*serie我认为它不会太.

有人能解释一下这些吗?

如果我想打印内容不应该放*而不是&,我认为使用动态数组[]而不是()它应该*serie[i]不是&serie[i]吗?

Dan*_*ego 5

在此代码中,serie是一个指向整数指针.该行为其malloc()分配空间,以便设置或获取整数到/从*serie将起作用.循环似乎错误地将rand()(整数)的返回值设置为serie.在您当前的代码中,该特定行应该如下所示(但它不是您想要的):

*serie = rand();
Run Code Online (Sandbox Code Playgroud)

因为rand()返回一个整数,而且serie单独是一个指向整数的指针.但是,*serie是一个可以设置为的整数.

printf(),你试图serie作为数组访问,但这不起作用因为你只分配了一个元素.好吧,它会起作用,但只适用于零元素.

如果您尝试设置并生成20个随机元素(但使用"动态"数组),您可能需要这样的内容:

int i;
// note allocating the proper number of elements
int *serie = malloc(sizeof(int) * 20);

// note starting at and going < 20 for 20 elements
for (i = 0; i < 20; i++) {
    serie[i] = rand();
    printf("%d ", serie[i]); // *(serie + i) will also work here
}
Run Code Online (Sandbox Code Playgroud)

请注意,每次使用方括号访问元素时,它都会取消引用它,就像它一样*.所以serie[i]并且*(serie + i)功能相同.