简体   繁体   English

如何将字符串放入带有 struct 的列表中? (C语言)

[英]how put string in a list with struct ? (C language)

main.c:主文件:

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

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

lista.h:列表.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:列表.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] lista.c:26:32: 警告:传递“strcpy”的参数 2 使指针从整数而不进行强制转换 [-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'在 lista.c:3 包含的文件中:/usr/include/string.h:125:70:注意:预期为“const char *restrict”,但参数的类型为“char”

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

ch is a single character and not a string (char[] / char*) ch 是单个字符而不是字符串 (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.您还应该确保 ch 确实以空字符结尾并且少于 50 个字符,否则如果是用户输入数据,他可以执行缓冲区溢出攻击。 i'd rather use strncpy/strlcpy here我宁愿在这里使用 strncpy/strlcpy

There are two distinct problems:有两个不同的问题:

  • in main is should be inserir(&p1, "Fabio"); main应该是inserir(&p1, "Fabio"); instead of void inserir(&p1, "Fabio");而不是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 ).在声明和inserir的实现中,它应该是void inserir(LISTA* l, const char *ch) (强调const char *ch )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM