Reputation: 13
In this code i want to user to input numbers in the function then print the array in the main method, but when i try to print in the main method it gives me random numbers.
for eg: 1 2 3 gives 1 3 1895586112
void arrayInput(int *arr) {
int x;
int y;
int z;
printf("enter 3 numbers =");
scanf("%d %d %d", &x,&y,&z);
arr[0]=x;
arr[1]=y;
arr[2]=z;
}
int main(int argc, char **argv){
int *arr[3];
arrayInput(&arr);
int i;
for(i=0; i<3; i++)
{
printf("%d ", arr[i]);
}
}
I want to change the array values without changing the method or param type
Upvotes: 1
Views: 279
Reputation: 2136
There are multiple issues with your code.
First you have declared int *arr[3];
which would mean pointer arrays. For your task a simple array is needed. The array variable contains the address of the first element, so you don't need &
.
A simple corrected code is as follows:
#include <stdio.h>
void arrayInput(int arr[]) {
int x;
int y;
int z;
printf("enter 3 numbers =");
scanf("%d %d %d", &x,&y,&z);
arr[0]=x;
arr[1]=y;
arr[2]=z;
}
int main(int argc, char **argv){
int arr[3];
arrayInput(arr);
int i;
for(i=0; i<3; i++)
{
printf("%d ", arr[i]);
}
}
Upvotes: 1
Reputation: 50774
int *arr[3]
is an array of pointers to int
. But you want an array of int
.
Simply change:
int *arr[3];
arrayInput(&arr);
to
int arr[3];
arrayInput(arr);
This should be covered in your C text book.
Bonus:
You can remplace this convoluted code:
void arrayInput(int *arr) {
int x;
int y;
int z;
printf("enter 3 numbers =");
scanf("%d %d %d", &x,&y,&z);
arr[0]=x;
arr[1]=y;
arr[2]=z;
}
with this:
void arrayInput(int *arr) {
printf("enter 3 numbers =");
scanf("%d %d %d", &arr[0],&arr[1], &arr[2]);
}
Upvotes: 1