访问结构数组中的下一个元素时 C 程序崩溃
C program crashes when accessing next element in array of struct
void struct_tokens(struct Words **w_count, int size)
{
*w_count = (struct Words*)calloc(size, sizeof(struct Words));
char *temp;
int n = 0;
int i = 0;
printf("Value 1: %s\n", (*w_count[0]).word);
printf("Value 2: %s\n", (*w_count[1]).word);
}
我的结构如下所示:
struct Words
{
char word[20];
unsigned int count;
};
它在我访问数组中的下一个元素时立即崩溃,因此访问 w_count[0] 但它无法访问 w_count[1] 而不崩溃。所以值 1 打印到控制台,但值 2 不打印,这是为什么?
calloc
调用是错误的 - 应该是
*w_count = calloc(size, sizeof(struct Words));
访问结构实例将是
printf("Value 1: %s\n", (*w_count)[0].word);
[]
的 precedence 高于 *
。在较早的情况下,您有未定义的行为(导致崩溃)。
另请注意,分配的内存将使用0
进行初始化。因此,char 数组将只包含 [=17=]
- 在 printf
.
中使用时不会打印任何内容
几点:
void*
到 struct Words *
的转换是隐式完成的 - 您不需要转换它。
检查 calloc
的 return 值,以防它 returns NULL
你应该适当地处理它。
使用完后释放动态分配的内存。 (使用 free()
)。
calloc
的正确代码应该是这样的:-
*w_count = calloc(size, sizeof(struct Words));
if( *w_count == NULL ){
perror("calloc");
exit(EXIT_FAILURE);
}
void struct_tokens(struct Words **w_count, int size)
{
*w_count = (struct Words*)calloc(size, sizeof(struct Words));
char *temp;
int n = 0;
int i = 0;
printf("Value 1: %s\n", (*w_count[0]).word);
printf("Value 2: %s\n", (*w_count[1]).word);
}
我的结构如下所示:
struct Words
{
char word[20];
unsigned int count;
};
它在我访问数组中的下一个元素时立即崩溃,因此访问 w_count[0] 但它无法访问 w_count[1] 而不崩溃。所以值 1 打印到控制台,但值 2 不打印,这是为什么?
calloc
调用是错误的 - 应该是
*w_count = calloc(size, sizeof(struct Words));
访问结构实例将是
printf("Value 1: %s\n", (*w_count)[0].word);
[]
的 precedence 高于 *
。在较早的情况下,您有未定义的行为(导致崩溃)。
另请注意,分配的内存将使用0
进行初始化。因此,char 数组将只包含 [=17=]
- 在 printf
.
几点:
void*
到struct Words *
的转换是隐式完成的 - 您不需要转换它。检查
calloc
的 return 值,以防它 returnsNULL
你应该适当地处理它。使用完后释放动态分配的内存。 (使用
free()
)。calloc
的正确代码应该是这样的:-*w_count = calloc(size, sizeof(struct Words)); if( *w_count == NULL ){ perror("calloc"); exit(EXIT_FAILURE); }