打印结构

时间:2017-04-25 01:47:46

标签: c

我想从c中的结构中打印元素,但send和第三个print语句给我警告:format指定类型'char *'但参数的类型为'char'。我知道它与指针有关,但我不知道我做错了什么。我还修改了它以显示我正在使用的2个结构。

struct student_record{
int student_id;
int student_age;
char first_name;
char last_name; };


struct student_record_node{
struct student_record* record;
struct student_record_node* next;
struct student_record_node* prev; };


void printNode(struct student_record_node *node){
printf("Struct student_record_node: \n");
printf("        student first_name: %s\n", node->record->first_name);
printf("        student last_name: %s\n", node->record->last_name);
printf("        student id: %d\n", node->record->student_id);
printf("        student age: %d\n", node->record->student_age);
printf("\n");}

2 个答案:

答案 0 :(得分:0)

在student_record的结构声明中

char first_name; char last_name;

表示first_name和last_name是两个字符,而不是字符数组(即字符串)

当使用printf(“%s”,ELEMENT)时,%s需要字符数组的内存地址,即。指针(char *)但是因为你传递了一个字符,所以它会导致语法错误。

要修复代码,请编辑结构声明,使其成为固定长度的静态数组,或者为函数中的字符指针动态分配内存。

答案 1 :(得分:0)

尝试这种方式:

#include<stdio.h>
#include<stdlib.h> 
#include<stdint.h>
#include<string.h>

struct student_record {
    int student_id;
    int student_age;
    char first_name;
    char last_name;
};

struct student_record_node {
    struct student_record* record;
    struct student_record_node* next;
    struct student_record_node* prev;
};

void printNode(struct student_record_node *node){
    printf("Struct student_record_node: \n");
    printf("        student first_name: %c\n", node->record->first_name);
    printf("        student last_name: %c\n", node->record->last_name);
    printf("        student id: %d\n", node->record->student_id);
    printf("        student age: %d\n", node->record->student_age);
    printf("\n");
}
int main()
{
    struct student_record_node* a = (student_record_node*)malloc(sizeof(student_record_node));
    a->record = (student_record*)malloc(sizeof(student_record));
    a->next = NULL;
    a->prev = NULL;

    a->record->first_name = 'f';
    a->record->last_name = 'l';
    a->record->student_age = 10;
    a->record->student_id = 99;
    printNode(a);

    free(a);
    return 0;
}

如果您想将名称设置为字符串,请使用char*代替char,格式说明符为%s,而不是%c