[英]segmentation fault (Core dumped) error on Dynamic array
I am having this issue when trying to build my dynamic array, I think that there is mystake on realloc function or something, would appreciate if you can give me a hand on it. 我在尝试构建动态数组时遇到了这个问题,我认为realloc函数之类的东西是我的错,如果您能帮助我的话,将不胜感激。 I am able to enter the names the first time but the issue start when Im doing it the second time
我第一次可以输入名称,但是第二次我输入时会出现问题
typedef struct {
char nom[30], prenom[20];
int age;
} ITEM;
void Lire(ITEM **items, int *nb_items)
{
int i = 0;
printf("* Entrer les donnees et taper . pour terminer\n\n");
for (i = 0; TRUE; i++)
{
ITEM *temp = (ITEM *) realloc(*items, ((i + 1) * sizeof(ITEM)));
if (temp == NULL)
{
free(*items);
printf("Il n'y a pas de memoire! \n");
exit (0);
}
*items = temp;
printf("> nom : ");
scanf("%s", (*items[i]).nom);
if ((*items[i]).nom[0] == '.')
break;
printf("> prenom : ");
scanf("%s", (*items[i]).prenom);
}
}
int main(int argc, char *argv[])
{
ITEM *items;
int nb_items=0;
items = (ITEM *) malloc(sizeof(ITEM));
if(items == 0)
{
printf("Il n'y a pas de memoire! \n");
exit (0);
}
Lire(&items, &nb_items);
free (items);
exit(0);
}
您的问题在于运算符的优先级: *items[i]
计算结果为items[i][0]
而您想要的是items[0][i]
,即:
(*items)[i]
Array subscript access binds tighter than *
. 数组下标访问的绑定比
*
更紧密。 This causes *items[i]
to be interpreted as *(items[i])
, for example in this statement: 这导致
*items[i]
被解释为*(items[i])
,例如在以下语句中:
scanf("%s", (*items[i]).nom);
So items
is accessed as if it would be an array of pointers to ITEM
. 所以
items
被访问,就好像它是指向数组ITEM
。 In reality it is a pointer to an array of ITEM
structs, and should be accessed like this: 实际上,它是指向
ITEM
结构数组的指针,应按以下方式访问:
scanf("%s", (*items)[i].nom);
to make life easier i would do 让生活更轻松
*items = temp;
ITEM *current = &temp[i];
printf("> nom : ");
scanf("%s", current->nom);
...etc
makes the code easier to read and simplifies the whole operator precedence isuuse 使代码更易于阅读,并简化了整个运算符的优先级isuuse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.