【问题标题】:Array for storing names and grades of students in C用于存储 C 中学生姓名和成绩的数组
【发布时间】:2014-11-03 05:14:18
【问题描述】:

我正在尝试用 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));
  }
}

【问题讨论】:

    标签: c arrays pointers dynamic-memory-allocation


    【解决方案1】:

    char *first, *last;
    

    您只能在变量中存储 1 个字符串,因为 C 中的字符串是 char *firstchar *first[i]char 所以你有与此相关的错误。您希望 first 成为 char **first[i] 作为 char *

    你想要

    char **first, **last;
    

    并将分配更改为(注意您不需要类型转换malloc

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

    然后在 for 循环中为 firstlast 中的每个 char * 分配内存,然后再读取其中的名称。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多