Assign string value with pre-defined size within the pointer

1

Need help with dynamic memory, I can not understand why I can not access nome of ptr in method adicionarSocio ?

How can I change this field? Do I have to malloc of the name before even assigning it already having the defined size?

Follow the code below:

typedef struct { 
  unsigned int nCliente, tel; 
  char nome[100 + 1]; 
  endereco morada; 
  emprestimos filmes[30]; 
} socio; 


void adicionarSocio(socio *ptr, int k) { 

  for (int i = 0; i < k; i++) { 
    printf("Introduza o seu nome:\n"); 
    char tmp[100 + 1]; 
    scanf(" %s", &tmp); 

    strcpy(ptr[i].nome, tmp); 
  } 
}

int main() {
    int qtde, op;
    socio *ap_socio;
    printf("Deseja espaço para quantos sócios?\n");
    scanf(" %d", &qtde);
    ap_socio = (socio*)malloc(qtde * sizeof(socio));
    if (ap_socio = NULL)
        printf("Erro\n");
    else {
        do {
            do {
                printf("Menu:\n");
                printf("Adicionar sócio ->1\n");
                printf("Alterar sócio ->2\n");
                printf("Remover sócio ->3\n");
                printf("Listar sócio ->4\n");
                printf("Alugueres ->5\n");
                printf("Sair - 0\n");
                scanf(" %d", &op);
            } while (op != 1 && op != 2 && op != 3 && op != 4 && op != 5 && op != 0);
            switch (op) {
            case 1:
                adicionarSocio(ap_socio, qtde);

                    printf("Sócio adicionado com sucesso!\n");

                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                listarSocio(ap_socio, qtde);
                break;
            case 5:
                break;
            }
        } while (op != 0);
    }
    free(ap_socio);
}
    
asked by anonymous 15.02.2018 / 19:04

1 answer

0

Try something like this

typedef struct _socio { 
  unsigned int nCliente, tel; 
  char nome[100 + 1]; 
  endereco morada; 
  emprestimos filmes[30]; 
} socio; 

typedef struct socio *Socio;

int main() {
    int qtde, op;
    printf("Deseja espaço para quantos sócios?\n");
    scanf(" %d", &qtde);
    Socio *ap_socio = malloc(size * sizeof(Socio));
    if (ap_socio = NULL)
        printf("Erro\n");
    else { ...

I believe that for you to be able to assign to each position of the array a struct should do this:

ap_socio[x] = NULL;
ap_socio[x] = malloc(sizeof(struct socio));
ap_socio[x] -> nome = ...;
etc ...

I've taken the following link , which in this case is a question on the stack itself.

See you later.

    
15.02.2018 / 20:22