应该打印整数。打印地址

时间:2012-08-02 13:02:21

标签: c pointers

我正在关注C的youtube上的教程系列。在这个特定视频(part 1part 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);
}

2 个答案:

答案 0 :(得分:7)

那些是对int的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;

您是否检查过编译器警告?

答案 1 :(得分:0)

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

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

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