当我尝试只使用 INT 参数时,它工作得很好,但是当我尝试使用字符串时,我总是得到“段错误”,我不知道为什么。
我知道这可能是一个愚蠢的错误,但是有人愿意向我解释一下吗?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct cliente{
char *nome;
int idade;
}t_cliente;
int main(){
t_cliente *vet;
int qtdCliente, i, j;
scanf("%d", &qtdCliente);
vet=(t_cliente*)malloc(qtdCliente*sizeof(t_cliente));
for(i=0; i<qtdCliente; i++){
scanf("%s", vet[i].nome);
scanf("%d", &vet[i].idade);
}
for(j=0; j<qtdCliente; j++){
printf("%s\n", vet[j].nome);
printf("%d\n", vet[j].idade);
printf("\n");
}
free(vet);
return 0;
}
最佳答案
vet=(t_cliente*)malloc(qtdCliente*sizeof(t_cliente));
(并且转换在 C 中既不必要又不明智)会给你一个结构数组,每个结构包含两个字段
nome
和 idade
.然而,
nome
在每个结构中都将设置为任意值,因此语句:scanf("%s", vet[i].nome);
几乎肯定会尝试写入它不应该写入的内存。
假设您知道第一个字段的最大大小是多少,最好将其定义为:
#define MAXNOME 50
typedef struct cliente{
char nome[MAXNOME];
int idade;
}t_cliente;
这样,您将尝试写入的内存至少是有效的。
但是,使用
scanf("%s",...)
的人通常没有意识到这是一种多么糟糕的做法。它可能会导致缓冲区溢出问题,因为无法对将写入缓冲区的字符指定限制。有更安全的方法来执行此操作(获取用户输入),例如找到的方法 here .
关于c - C中扫描和打印字符串的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662911/