I can’t copy a string array to a string array in a struct

Asked

Viewed 62 times

0

I’ve been racking my brain for hours, and I can’t seem to fix it. I want to copy a new string and place it in the first position of a string array in a struct. However, when I try to copy the new value that will be added to the first position simply from an error ("error: assignment to Expression with array type"). I’m starting now on programming, so please forgive me for layering.

Follow the code below:

#include <stdio.h>

typedef struct{
    char nome[30];
    int rg;
}PESSOA;

PESSOA *alocaMemoria(int tam){
    PESSOA *v;

    v=(PESSOA*)(malloc(tam*sizeof(PESSOA)));

    return v;
}

void adicionaValor(PESSOA *vetor, int tam){
    int i;

    for(i=0;i<tam;i++){
        printf("Nome: ");
        scanf("%s", &vetor->nome);
        printf("RG: ");
        scanf("%d", &vetor->rg);
    }
}

void mostraVetor(PESSOA *vetor, int tam){
    int i;
    PESSOA *pVetor;

    pVetor=vetor;

    for(i=0;i<tam;i++){
        printf("Nome: %s\n", pVetor->nome);
        printf("RG: %d\n", pVetor->rg);
    }
}

void adicionaInicio(PESSOA *vetor, int tam, char *nome, int rg){
    PESSOA *novoVetorAux;

    novoVetorAux[0].nome=nome;
    novoVetorAux[0].rg=rg;

}

int main(){

    PESSOA *vetor;
    int tam, op, rg;
    char nome[30];

    printf("Selecione a opcao desejada: ");
    scanf("%d", &op);

    printf("1 - Inicia vetor\n");
    printf("2 - Adiciona valores as casas do vetor\n");
    printf("3 - Adiciona valores a primeira casa do vetor\n");
    printf("6 - Mostra Vetor em ordem\n");

    switch(op){
        case 1:
            printf("Tamanho do vetor: ");
            scanf("%d", &tam);

            vetor=alocaMemoria(tam);
        break;

        case 2:

            adicionaValor(&vetor, tam);
        break;

        case 3:
            printf("Nome: ");
            scanf("%s", &nome);
            printf("RG: ");
            scanf("%d", &rg);

            adicionaInicio(&vetor, tam, &nome, rg);
        break;

        case 6:
            mostraVetor(&vetor, tam);
        break;
    }



return 0;
}

1 answer

0


c-strings are not "assignable" that way. You need to copy, in fact, character by character, from one array to the other. To do this, use the function strcpy() defined in the header string.h.

I have not tested your code, but it seems to me that you have more problems than just this... Anyway, to use the function, do:

strcpy( arrayDestino, arrayOrigem );

Browser other questions tagged

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