gpt4 book ai didi

calloc 在 char 数组中返回少 2 个字符

转载 作者:行者123 更新时间:2023-11-30 18:31:56 29 4
gpt4 key购买 nike

海湾合作委员会(GCC)4.4.6

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct B {
int i;
char *p;
} B_t;

B_t b = {
.i = 10,
.p = NULL
};

int main(int argc, char *argv[])
{

struct B *ptr;

ptr = &b;

ptr->p = (char *) calloc(ptr->i, sizeof(char));

printf("%d,%lu,%lu\n", ptr->i, sizeof(ptr->p), sizeof((ptr->p)[0]));

return 0;
}

$ make
gcc -g -Wall -o test test.c
$ ./test
10,8,1

为什么?我期待 10,10,1

最佳答案

p 是指向 char 的指针。 sizeof() 运算符应用于指针时将返回指针中的字节数,而不是为指向的对象分配的内存量。在您的系统上,指针的大小为 8 个字节,因此您看到的是 8。

关于calloc 在 char 数组中返回少 2 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18437571/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com