Can someone explain me, please, why can't I insert values into a struct array.
Here's a piece of my code to help understand what I'm trying to accomplish.
I want to insert values inside an array which is formed by structs, whenever I try to insert values it gives me a segmentation error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAM_TABELA 10
#define PRIMO 7
#define MAX_NOME 50
typedef struct {
char nome[MAX_NOME];
int telemovel;
} pessoa;
void insert(pessoa *grupo[]) {
char nome[MAX_NOME];
printf("\nInsert name:\n");
scanf("%s", nome);
int lenght = strnlen(nome, MAX_NOME);
printf("\nInsert phone:\n");
scanf("%d", &tel);
for (i = 0; i < TAM_TABELA; i ) {
if (grupo[i] == NULL) {
grupo[i]->telemovel = tel;
strcpy(grupo[i]->nome, nome);
break;
}
}
if (i == TAM_TABELA)
printf("\nO valor não pode ser inserido!\n");
}
void main() {
int opt;
pessoa p;
pessoa grupo[TAM_TABELA] = {NULL};
insert(grupo);
}
CodePudding user response:
- You need to pass the address of
grupo
toinsert()
function. int main(void) { }
is a valid Cmain()
functionsize_t
is a valid data type for lengths, iterate through arrays- Always check whether
scanf()
conversion was successful or not - Do not use
"%s"
, use"%<WIDTH>s"
, to avoid buffer-overflow for( i = 0; i < TAM_TABELA; i )
i
was never defined- parameter of the function
insert()
should bepessoa ***grupo
, in de-reference it later in your function like*grupo
- Initialize your
char []
using{}
, which are stored on stack memory
CodePudding user response:
for (i = 0; i < TAM_TABELA; i ) { if (grupo[i] == NULL) { grupo[i]->telemovel = tel; strcpy(grupo[i]->nome, nome); break; } }
Notice how you've checked that grupo[i]
is NULL
and then you try to access a struct member on that value that is NULL
.
You possibly want to check that grupo[i] != NULL
, which should make member access safe.