简体   繁体   中英

C Basic scanf not working

int g1,g2,g3,g4;
scanf("%d %d %d %d", &g1, &g2, &g3, &g4);
g[0] = g1;
g[1] = g2;
g[2] = g3;
g[4] = g4;

For whatever reason g[4] is not registered. I'm not exactly sure what the problem is, anyone have any input?

I think you meant to set g[3] = g4 instead of g[4] = g4 . If your array is size 4 then the last element will be at index 3 .

Please ensure the array "g" is declared and it is of size 5. This will allocate memory that can be accessed by array index 0,1,2,3 and 4. According to the below code, g[3] is never used but has allocated memory.

Assuming you are using integer array, below is the syntax that works fine:

    int g[5];
    int g1,g2,g3,g4l;
    scanf("%d %d %d %d", &g1, &g2, &g3, &g4);
    g[0] = g1;
    g[1] = g2;
    g[2] = g3;
    g[4] = g4;

Thanks

#include<stdio.h>
main(){
int g1,g2,g3,g4,g[4];
        scanf("%d %d %d %d", &g1, &g2, &g3, &g4);
        g[0] = g1;
        g[1] = g2;
        g[2] = g3;
        g[3] = g4;
printf("%d\t%d\t%d\t%d",g[0],g[1],g[2],g[3]);
return 0;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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