无法从 C 中的结构打印字符串

标签 c string struct printing strcpy

typedef struct listaDocente nodoDocente;
struct listaDocente{            //teacherList
    char Rut[12];               //ID
    char Nombre[50];            //Name
    char Correo[70];            //Email
    char Cod_Curso[6];          //Grade_Code
    char Asignatura[15];        //Grade_Name
    nodoDocente *siguiente;     //Next (Node)
};

int main(){
    nodoDocente *D = ((nodoDocente * )malloc(sizeof(nodoDocente)));
    strcpy(D->Nombre, "Charlie");
    strcpy(D->Rut, "18123456");
    strcpy(D->Asignatura, "EDD");
    strcpy(D->Cod_Curso, "INS123");
    strcpy(D->Correo, "charlie@test.com");
    printf("%s\n", D->Nombre);
    printf("%s\n", D->Rut);
    printf("%s\n", D->Asignatura);
    printf("%s\n", D->Cod_Curso);
    printf("%s\n", D->Correo);

    return 0;
}

首先,抱歉,如果有些词是西类牙语。 我试图打印这些值,但我得到了一个空白。

Charlie
18123456

INS123
charlie@test.com

它应该在哪里打印出 EDD,就像这样。

Charlie
18123456
EDD
INS123
charlie@test.com

最佳答案

您已声明:

char Cod_Curso[6];

并填充它:

strcpy(D->Cod_Curso, "INS123");

但是 INS123 后面是字符串的终止字符 \0。因此,字符串 INS123 实际上占用 7 个字符,而不是您可能认为的 6 个字符。因此,您不能期望声明:

printf("%s\n", D->Asignatura);

在您调用 时正常工作与上一行。

解决方案:声明 Cod_Curso 的大小为 7(或更大),如下所示:

char Cod_Curso[7];

另外,看看这个 link on why not to cast the result of malloc .

关于无法从 C 中的结构打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37453018/

相关文章:

c - 将指针传递给多维数组

c# - 如何在我的字符串中插入 '-'?

objective-c - NSString sizeWithFont :constrainedToSize:lineBreakMode: differs from actual Label height

inheritance - 具有混合结构类型的 Go 映射和 slice

go - 用结构解码复杂的 JSON 广告

c - "Hello world"程序未运行

c - 用随机数据填充内存区域

c - "undefined reference to strerror_r"与 OpenSSL-1.1.0e 和 MinGW

jquery - 更改字符串

使用 C 将输入与 txt 文件中的数据进行比较