I know its something simple but I cant figure out why my array is not printing once the user enters the size and integers. I finally was able to get the user to determine the size of the array and enter their own integers but now the program returns right after.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
//Declare a size variable
int size = 0;
//Ask user how many numbers are in list:
printf("How many integers?");
scanf("%d", &size);
printf("Please enter integers:");
int arr[size];
scanf("%d", arr);
//Calculate length of array
int length = sizeof(arr)/sizeof(arr[0]);
//Test print to see if array is returning the right amount of integers.
//printf("%d", length);
//Print original array
for(int i = 0; i > length; i )
{
printf("%d", arr[i]);
}
printf("\n");
return 0;
}
CodePudding user response:
scanf("%d", arr);
Because arr
now is a pointer to arr[0]
, scanf("%d", arr);
will just input the first element of the array.
You have to put it in a for
loop:
for(int i = 0; i < size; i)
{
scanf("%d", &arr[i]);
}
This for
loop:
for(int i = 0; i > length; i )
{
printf("%d", arr[i]);
}
will never executed, because length
is always larger than 0
, so when i = 0
, i > length
is false
.
You should use:
for(int i = 0; i < length; i )
{
printf("%d", arr[i]);
}
Also, length
is just size
, so you don't need length
So your code should be:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int size = 0;
printf("How many integers?");
scanf("%d", &size);
printf("Please enter integers:");
int arr[size];
for(int i = 0; i < size; i)
{
scanf("%d", &arr[i]);
}
for(int i = 0; i < size; i )
{
printf("%d", arr[i]);
}
printf("\n");
return 0;
}