2017-04-25 83 views
-2

我想打印c中结构的元素,但send和third打印语句给了我警告:格式指定类型'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");} 
+1

显示结构声明。 – Barmar

+3

它与指针没有任何关系。错误消息说'first_name'和'last_name'被声明为'char',而不是'char [some_size]'或'char *'。 – Barmar

+0

你确定你得到第三个'printf'的错误,而不是前两个?顺便说一句,最后一个'printf'在结尾处缺少'';' –

回答

0

在student_record

炭如first_name的结构声明; char last_name;

指示如first_name和last_name是两个字符,而不是字符阵列(即字符串)

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

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

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