2017-04-25 81 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