Pedro
Pedro

Reputation: 489

Function to save data as struct on C

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

 typedef struct equipamento { 
    int codDipositivo;
    char nomeEquipamento[40];
    char newVar[50];
}Equipamento;

insert(int n, int cat, Equipamento eq[])
{
    int codigo;
    char newVar[40];
    printf("\nNew Var: ");  
    scanf("%s",&newVar);    
    eq[n].codDipositivo=newVar;
}

main()
{
    Equipamento equipamento[MAX_EQ_DSP];


    ...a bunch of scanfs 
    scanf("%d",&n);
    scanf("%d",&pr);


    insert(n, pr, equipamento);
}

This is a sample of what I have.

on main I have a bunch of scanfs which will update the data showing on the screen but now I want to pass that data into a structure and ask for additional information.

I'm trying to use the updated code but for some reason, instead of 39 chars, it breaks down (returns to the main cycle) after the first char

printf("\nNome do Equipamento: "); 
gets(nome);
strcpy(eq[n].nomeEquipamento, nome);

Upvotes: 0

Views: 3165

Answers (1)

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

Your problem is this line:

eq[n].codDipositivo=newVar;

In C, you cannot assign arrays, you need to copy them element for element. Remember that C has no string data type, a string is just a NUL-terminated array of char. Luckily there is a function in the C library to help us, strcpy.

strcpy(eq[n].codDipositivo, newVar);

To get the declaration of strcpyyou need to add the following include at the top of your code:

#include <string.h>

Upvotes: 1

Related Questions