我正在嘗試學習 C,我有一個使用 malloc 和 struct 的分配,我讓它列印出佇列號,但字串不會列印。我附上了列印的圖片,但僅在 strcpy 被注釋掉并且我無法弄清楚時才有效。
誰能解釋我做錯了什么以及應該怎么做?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct car
{
int queue;
char *Regnr;
char *Manufactor;
char *WashType;
char *CarId;
struct car *next;
};
typedef struct car CarWash;
/* print the list out from ... */
void printlist (CarWash * head)
{
CarWash *temp = head;
while (temp != NULL)
{
printf ("%d\t\t %s\t\t %s\t\t %s\t \n", temp->queue, temp->Regnr,
temp->Manufactor, temp->WashType);
temp = temp->next;
}
printf ("\n");
};
CarWash *create_new_queue(int val,char CarId)
{
CarWash *result = malloc (sizeof (CarWash));
char strcpy(char Regnr, char CarId);
result->Regnr = CarId;
result->queue = val;
result->next = NULL;
return result;
};
已編輯
int
main ()
{
int queue;
char Regnr[10];
char Manufactor[10];
char WashType[10];
char CarId[10];
CarWash *head;
CarWash *tempB;
FILE *fp;
fp = fopen ("Car wash.txt", "r");
fscanf (fp, "%d%s%s%s", &queue, Regnr, Manufactor, WashType);
fclose (fp);
printf (" \n"); //voodoo to show my printlist
tempB = create_new_queue (queue, Regnr);
head = tempB;
printf ("%s\t %s\t\t %s\t %s\n", "k? plads", "Regnr", "Manufactor",
"vaske type");
printlist (head);
return 0;
}
已編輯
列印的內容:

uj5u.com熱心網友回復:
你可能想要這個:
struct car
{
int queue;
char Regnr[10]; // don't declare pointers but arrays
char Manufactor[10];
char WashType[10];
char CarId[10];
struct car *next;
};
和更正的create_new_queue功能:
CarWash* create_new_queue(int val, char *CarId) // add the *, CarId is not a char
{
CarWash* result = malloc(sizeof(CarWash));
strcpy(result->Regnr, CarId); // actually call strcpy
result->queue = val;
result->next = NULL;
return result;
};
我建議您閱讀學習材料中處理指標的章節和處理字串的章節。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462105.html
上一篇:你可以在C中按值傳遞字串嗎?
下一篇:如何從檔案中讀取并決議它
