Home > database >  how put string in a list with struct ? (C language)
how put string in a list with struct ? (C language)

Time:10-09

main.c:

#include "lista.h"
#include <stdio.h>

int main(void){
    LISTA p1;
    iniciaLista(&p1);
    inserir(&p1, "Fabio");
    return 0;
}

lista.h:

#include <stdio.h>
#include <stdbool.h>

#define MAX 60

typedef struct{
   char nome[50];
}REGISTRO;

typedef struct{
    REGISTRO A[MAX  1];
    int qtdElemen;
}LISTA;

void iniciaLista(LISTA* l);
void inserir(LISTA* l, char ch);

lista.c:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "lista.h"

void iniciaLista(LISTA* l){
    l->qtdElemen = 0;
}
void inserir(LISTA* l, char ch){
    int i = l->qtdElemen;
    if(l->qtdElemen == MAX) return;
    else{
        strcpy(&ch, (l->A[i].nome);
        l->qtdElemen  ;
    }
    return;

}

i'm trying put a name in a list but i cant and dont know why, What can I be doing wrong?, I get several errors when I try to run:

lista.c:26:32: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]

In file included from lista.c:3: /usr/include/string.h:125:70: note: expected ‘const char * restrict’ but argument is of type ‘char’

CodePudding user response:

void inserir(LISTA* l, const char ch);

ch is a single character and not a string (char[] / char*)

you also should make sure that ch is really null terminated and with less than 50 characters ortherwise if it's the user that inputs data he can perform a bufferoverflow attack. i'd rather use strncpy/strlcpy here

CodePudding user response:

There are two distinct problems:

  • in main is should be inserir(&p1, "Fabio"); instead of void inserir(&p1, "Fabio");
  • in the declaration and the implementation of inserir it should be void inserir(LISTA* l, const char *ch) (emphasis on const char *ch).
  • Related