繁体   English   中英

即使在 c 中声明变量后,程序也会返回垃圾值

[英]program returning garbage values even after declaring variables in c

我如何纠正这个

我没有故意使用结构 这是一个输入学生姓名、科目和分数的程序。 在最后一个块中,数组 (subject+f) 的第一个下标返回垃圾值,而其余下标返回所需的结果。 我还发布了输出图像作为链接。

#include<stdio.h>
#include<string.h>
int main()

{

int size,i,k,sub,a=0,reference;


    int temp,sorted;
    char temp_s[10];
    char temp_sb[10];

    printf("enter the size of class\n");
    scanf("%d",&size);
    printf("how many subjects are there?\n");
    scanf("%d",&sub);
    reference = sub;
    char name[size][20];
    char subject[size*sub][20];
    int marks[sub*size];
    int total,subtotal,retotal;
    for(k=0;k<sub;k++)
    {
    printf("so what's  the no. %d subject\n",k+1);
    scanf(" %s",(subject[k]));
    }

    for(i=0;i<size;i++)
        {

            int j,k=0;
            printf("Enter a name of student %d\n",i+1);
            scanf(" %s",(name+i));


                for(j=a;j<reference;j++)
                {
                    printf("enter marks of %s\n",(subject[k]));
                    scanf("%d",(marks+j));
                    k++;
                }

                a=j;
                reference=sub+j;


        }

    reference=sub;
    a=0;


    printf("\n list of students and marks:\n");
    for(i=0;i<size;i++)
        {
            int j,f=0;
            printf("%s\n",(name+i));
            for(j=a;j<reference;j++)
            {
                 printf("%s %d\n",(subject[f]),(marks[j]));
                 f++;
            }
            a=j;
            reference=sub+j;

        }
}

除了名称和主题的长度问题外,这是一个主要问题:

(subject+k)

您可能误解了subject[k]*(subject + k)等价物。

变量subject是一个数组数组。 这意味着subject[i]是一个数组( char并且可以用作以零结尾的字符串)。

表达式(subject + k)是指向subject[k]的数组的指针。 它等于&subject[k]类型为char (*)[10] 它不能在不取消引用的情况下用作以零结尾的字符串。 因此,要么使用*(subject + k)要么使用简单的、编写较少且易于阅读的subject[k]

我觉得你也需要改变

int marks[sub];

int marks[size * sub];

每个学生每个科目一分,对吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM