【发布时间】:2017-06-13 14:11:03
【问题描述】:
以下代码取自本网站的示例。我不明白,我做错了什么?你能帮帮我吗?
编译:
gcc -std=c11 main.c
仅打印:
东西:煮荞麦,重量:1500
分段错误
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
typedef struct {
// Weight in grams
size_t weight;
// Name of Thing
char name[255];
} Things;
void add_new_thing(Things **things,size_t *size)
{
size_t index = *size;
if(index == 0){
(*size) = 1;
*things = (Things*)calloc((*size),sizeof(Things));
if (*things == NULL) {
fprintf(stderr, "Error: can't allocate memory! %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}else{
(*size) += 1;
Things *temp = (Things*)realloc(*things,(*size)*sizeof(Things));
if(temp != NULL) {
*things = temp;
}else{
fprintf(stderr, "Error: can't reallocate memory! %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
// Zeroing of new structure's elements
things[index]->name[0] = '\0';
things[index]->weight = 0;
}
}
void another_function(Things *things,size_t *size)
{
// Add one element to the array of structures
add_new_thing(&things,size);
const char *str1 = "Boiled buckwheat";
strncpy(things[*size-1].name, str1, strlen(str1) + 1);
things[*size-1].weight = 1500;
for(size_t i = 0;i < *size;i++){
printf("Thing: %s, weight: %zu\n",things[i].name,things[i].weight);
}
// Add one more element to the array of structures
add_new_thing(&things,size);
const char *str2 = "A toy";
strncpy(things[*size-1].name, str2, strlen(str2) + 1);
things[*size-1].weight = 350;
// Segmentation fault is below
for(size_t i = 0;i < *size;i++){
printf("Thing: %s, weight: %zu\n",things[i].name,things[i].weight);
}
}
void some_function(Things *things,size_t *size)
{
// To pass the array of structures to another function
another_function(things,size);
}
int main(void)
{
// Create NULL pointer for the array of structures
Things *things = NULL;
// Add size of structures' array which will be allocated within add_new_thing() function
size_t size = 0;
// Call some function
some_function(things,&size);
// Segmentation fault is below
printf("Print results:\n");
for(size_t i = 0;i < size;i++){
printf("Thing: %s, weight: %zu\n",things[i].name,things[i].weight);
}
free(things);
return(EXIT_SUCCESS);
}
【问题讨论】:
-
您介意提供minimal reproducible example吗?
-
some_function如果只是用来调用另一个函数,它的本质是什么。为什么不将things的地址直接传递给另一个函数 -
对于您的
add_new_thing函数来说更有意义,它还可以为您正在创建的新“事物”获取值 -
你的代码很糟糕,关于你的
things指针没有改变。
标签: c arrays struct segmentation-fault dynamic-allocation