I was trying to a simple program of passing the inputted numbers of the arrays and displaying it using the function but it shows random value. What am I doing wrong?
#include<stdio.h>
#define size 5
void display();
int main()
{
int arr[size];
int i;
for(i = 0; i < size; i ){
printf("Input a number at index %d: ", i);
scanf("%d", &arr[i]);
}
display();
}
void display(){
int i;
int arr[size];
for(i = 0; i < 5; i )
printf("Element[%d] = %d\n", i, arr[i]);
}
CodePudding user response:
You have two arrays with the same name but different scope. A variable declared in a function is not visible outside of an function. In your case the one stores the numbers and the one gets printed but they are not the same. Moving int arr[size];
to global scope would resolve this problem related to scope.
#include<stdio.h>
#define size 5
int arr[size];
void display(){
for(int i = 0; i < 5; i )
printf("Element[%d] = %d\n", i, arr[i]);
}
int main()
{
for(int i = 0; i < size; i ){
printf("Input a number at index %d: ", i);
scanf("%d", &arr[i]);
}
display();
}
A better solution would be to avoid global variables and use a pointer to pass your array to the display function.
#include<stdio.h>
#define size 5
void display(int *arr){
for(int i = 0; i < size ; i )
printf("Element[%d] = %d\n", i, arr[i]);
}
int main()
{
int arr[size];
for(int i = 0; i < size; i ){
printf("Input a number at index %d: ", i);
scanf("%d", &arr[i]);
}
display(arr);
}
CodePudding user response:
You can't pass an array, but you can pass a pointer into it instead.
void print_elements(int *array, int length) {
for (int i = 0; i < length; i ) {
printf("%d", array[i]);
}
}
int foo[size];
print_elements(foo, size);
CodePudding user response:
You did not pass the array as an argument to the function, functions can only access variables passed as arguments or global variables. i changed your code a bit and added some checks for invalid values, now it should work.
#include<stdio.h>
#define SIZE 5
void display(int*, int);
int main()
{
int arr[SIZE];
int i;
for(i = 0; i < SIZE; i ){
printf("Input a number at index %d: ", i);
int res = scanf("%d", &arr[i]);
if (res != 1) {
printf("Not a valid integer scanned!");
return -1;
}
}
display(arr, SIZE);
}
void display(int* arr, int size){
if (arr == NULL) {
printf("Error! Null array!");
return;
}
for(int i = 0; i < size; i )
printf("Element[%d] = %d\n", i, arr[i]);
}