Home > Software engineering >  Change values in a struct array
Change values in a struct array

Time:04-20

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:

  1. You need to pass the address of grupo to insert() function.
  2. int main(void) { } is a valid C main() function
  3. size_t is a valid data type for lengths, iterate through arrays
  4. Always check whether scanf() conversion was successful or not
  5. Do not use "%s", use "%<WIDTH>s", to avoid buffer-overflow
  6. for( i = 0; i < TAM_TABELA; i ) i was never defined
  7. parameter of the function insert() should be pessoa ***grupo, in de-reference it later in your function like *grupo
  8. 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.

  • Related