Assign string value with pre-defined size inside the pointer

Asked

Viewed 62 times

1

You need help with dynamic memory, I can’t understand why I can’t access nome of ptr in the method adicionarSocio?

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

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);
}
  • What is the purpose of the add-in function? Register a partner ? If so, what is the purpose of the go-to qtd ?

1 answer

0


Try something like that

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 later for you to be able to assign each position of the array to a struct you should do this:

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

I took as a basis the following link, which in case is a doubt in the stack itself.

See you around.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.