0

我正在关注 C 的 youtube 上的教程系列。在这个特定的视频(第 1部分,第 2 部分)中,他制作了一个成绩单程序。据我所知,我的代码和他的完全一样,但是当我打印出成绩的整数时,它会打印出整数的地址。但它确实可以很好地打印出字符串。代码:

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

typedef struct {
    char *name;
    int science, history, math, english;

} reportCard;

void printReportCard(reportCard *rc);

int main() {
    reportCard r1;
    r1.name = "Daniel Pendergast";
    r1.science = "80";
    r1.history = "90";
    r1.math = "100";
    r1.english = "80";

    printReportCard(&r1);
    return 0;
}

void printReportCard(reportCard *rc) {
    int average = (rc->science + rc->history + rc->math + rc->english) / 4;
    printf("Student's name: %s\nScience grade: %i\nHistory grade: %i\nMath grade: %i\nEnglish grade: %i\nOVERALL GRADE: %i",
    rc->name, rc->science, rc->history, rc->math, rc->english, average);
}
4

2 回答 2

7

这些是将 char 指针分配给整数(如果不清楚,则无效):

r1.science = "80";
r1.history = "90";
r1.math = "100";
r1.english = "80";

应该:

r1.science = 80;
r1.history = 90;
r1.math = 100;
r1.english = 80;

你检查编译器警告了吗?

于 2012-08-02T13:03:55.070 回答
0

r1.science = "80";- 这将80作为字符串保留在文本段(只读数据)中,然后将该字符串的虚拟地址分配80r1.science.

将值分配为整数,如下所示

r1.science = 80; 
r1.history = 90; 
r1.math = 100; 
r1.english = 80;
于 2012-08-02T14:02:30.650 回答