Using functions and arrays
My little program below shall take 5 numbers from the user, store them into an array of integers and use a function to print them out. Sincerly it doesn't work and my output is always "00000". I can't find a mistake, so i would be glad about any advice. Thanks.
#include <stdio.h>
void printarray(int intarray[], int n)
{
int i;
for(i = 0; i < n; i ++)
{
printf("%d", intarray[i]);
}
}
int main ()
{
con开发者_运维知识库st int n = 5;
int temp = 0;
int i;
int intarray [n];
char check;
printf("Please type in your numbers!\n");
for(i = 0; i < n; i ++)
{
printf("");
scanf("&d", &temp);
intarray[i] = temp;
getchar();
getchar();
}
printf("Do you want to print them out? (yes/no): ");
scanf("%c", &check);
if (check == 'y')
printarray(intarray, n);
getchar();
getchar();
return 0;
}
You want %d
, not &d
, in your scanf()
format string. This bug is the kind that is very easy to identify by using a debugger - I recommend learning how to use whichever one works best with the rest of your development system.
Compiling with more warnings turned on would probably have detected this one, too. Something like "too many arguments for format".
精彩评论