Re: [問題] 鏈結串列的字串列印問題
※ 引述《win900702 (阿中)》之銘言:
: ( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 )
: ( 未必需要依照此格式,文章條理清楚即可 )
: 遇到的問題: (題意請描述清楚)
: 在鏈結串列中有放入字串資料
: 原本想用char name[][]的二維陣列去存
: 但是在print的時候字串會變成亂碼QQ
: 是改printlist的function還是改當初宣告的方式?
: 這個部分應該要怎麼修改呢?
: 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
: Dev -C++
: 有問題的code: (請善用置底文標色功能)
: #include<stdlib.h>
: #include<stdio.h>
: struct node
: {
: int num;
: char name[10];
: float weight;
: int sex;
: int score;
: struct node *next;
: };
: typedef struct node NODE;
: NODE *createlist(int *,char *,int *,float *,int *,int);
: void printlist(NODE *);
: void freelist(NODE *);
: int main(void){
: int i;
: NODE *first;
: int num[]={109,201,159,163,200};
: float weight[]={79.1,60.3,81.4,76.6,62.3};
: char name[5][10]={"John","Mary","Peter","Kelly","Gloria"};
: int sex[]={0,1,0,1,0};
: int score[]={100,70,60,80,50};
: first=createlist(num,name[10],sex,weight,score,5);
name[10] ?! 你想幹嘛?
: printlist(first);
: freelist(first);
: system("pause");
: return 0;
: }
: NODE *createlist(int *num,char *name, int *sex,float *weight,int *score,int
: len)
: {
: int i;
: NODE *first,*current,*previous;
: for(i=0;i<len;i=i+1){
: current=(NODE *)malloc(sizeof(NODE));
: current->num=num[i];
: current->name[i]=name[i];
current->name[i] ?!
所以你打算設定第一個節點的name[0],而name[1]~[9]不設定?
第二個節點的name[1],而name[0]和name[2]~[9]不設定?
....
: current->weight=weight[i];
: current->sex=sex[i];
: current->score=score[i];
: if(i==0){
: first=current;
: }
: else{
: previous->next=current;
: }
: current->next=NULL;
: previous=current;
: }
: return first;
: }
: void printlist(NODE *first)
: {
: NODE* node=first;
: if(first==NULL){
: printf("list is empty!\n");
: }
: else{
: while(node!=NULL)
: {
: printf("num=%d\t",node->num);
: printf("name=%s\t",node->name);
: printf("weight=%0.1f\t",node->weight);
: printf("sex=%d\t",node->sex);
: printf("score=%d\t",node->score);
: node=node->next;
: printf("\n");
: }
: }
: }
: void freelist(NODE *first)
: {
: NODE *current,* tmp;
: current=first;
: while(current!=NULL){
: tmp=current;
: current=current->next;
: free(tmp);
: }
: }
: 補充說明:
: 如果可以麻煩回答的大大儘量解釋得清楚些^^
: 因為小弟學C到目前才學一學期XP
: 謝謝您的回答!!
假設你打算用char name[5][10]={"ABCD","Mary","Peter","Kelly","Gloria"};
傳進去createlist的話,請宣告成 NODE *createlist( ,char name[][10], , )
並將 current->name[i]=name[i]; 修改成下面這樣
for( j=0;j<10;j++)
{
current->name[j] = name[i][j];
}
如果你想直接 current->name=name[i];
請把你的
struct node
{
int num;
char *name; // name[10]
float weight;
int sex;
int score;
struct node *next;
};
------------------------------------------------------
如果覺得 NODE *createlist( ,char name[][10], , ) 太醜!!
那改成 NODE *createlist( ,char **name, , )
在你的main function加個
char **temp = (char**)malloc(sizeof(char)*5);
for( int j = 0; j< 5;j++)
{
temp[j] =name[j];
}
first=createlist(num,temp,sex,weight,score,5);
希望有幫助到你~~~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.227.184.106
推
01/11 04:27, , 1F
01/11 04:27, 1F
討論串 (同標題文章)