2014-11-03 55 views
-1

我想在C中製作一個小程序,它將存儲用戶輸入的學生人數的名字,姓氏和成績。到目前爲止,我最大的問題是如何獲得每個學生的姓名和成績,以新的方式進行打印。對於字符串運算符,我得到一個錯誤,並且對於char運算符,我只能得到第一個字母和等級。我將如何着手讓名稱完全打印?感謝您提前提供的所有幫助。用於存儲學生姓名和成績的數組C

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


int main(){ 
    int classsize,i; 

    printf("Please indicate number of records you want to enter (min 5, max 15):\n"); 
    scanf("%d", &classsize); 

    char *first, *last; 
    double *mark; 

    first=(char*)malloc(classsize*sizeof(char)); 
    last=(char*)malloc(classsize*sizeof(char)); 
    mark=(double*)malloc(classsize*sizeof(double)); 



    printf("Please input records of students (enter a new line after each record), with following format 1. first name 2. last name 3. score.\n"); 
    for (i=0; i<classsize; i++) { 
    scanf("%s", &first[i]); 
    scanf("%s", &last[i]); 
    scanf("%lf", &mark[i]); 
    } 

    for (i=0; i<classsize; i++) { 
    printf("%s, %s has a %lf\n", *(first+i), *(last+i), *(mark+i)); 
    } 
} 

回答

2

隨着

char *first, *last; 

您可以在變量字符串中C只能存儲1串char *firstchar *first[i]char因此您有與此相關的錯誤。你想要firstchar **first[i]char *

你想

char **first, **last; 

,並更改分配(注意您不必強制轉換malloc

//---------------------------------v 
first=malloc(classsize*sizeof(char *)); 

然後在for循環first分配每個char *內存和在讀那個名字之前的last

first[i] = malloc(some_size * sizeof(char)); 
... 
+0

謝謝!非常豐富。 – Kenshin 2014-11-03 05:31:49

相關問題