Reputation: 1
This is my code
#include<stdio.h>
int main()
{
int n,a[n],op;
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[n]);
}
printf("Select array element to display from 1 to %d\n",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %d\n",a[op-1]);
}
else
{
printf("Invalid Entry\n");
}
return 0;
}
Output
Enter size of the array
5
Enter the array elements
2
5
6
1
5
Select array element to display from 1 to 5
2
Element is 0
Why is this happening? I couldn't figure this out
Upvotes: 0
Views: 60
Reputation: 881113
Consider your code:
int n,a[n],op;
Given that the value of n
is undefined at this point, the variable length array (VLA) created by a[n]
will be of some arbitrary size. C doesn't magically reach back in time from the point where you request a value of n
and adjust the array size :-)
You need to create the VLA after you've set the value of n
, reorganising your code at the start of main
with something like this:
int n,op;
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n];
That way, n
will be a known value when you use it to create the VLA.
Additionally, your scanf("%d",&a[n]);
is undefined behaviour because n
will always be beyond the end of the array (which has indexes 0
through n-1
inclusive). You should be using i
as the index there.
There are other logic issues such as checking that the scanf
succeeded and that you didn't enter a non-positive number but that's usually okay for educational code (assuming that's what this is). As you develop as a coder, you will naturally begin to think of these possibilities and harden your code accordingly.
By way of example, this is a better way to enter n
, although you could recover from non-numeric data as an optional extra (see here for a nifty line input solution in C):
int n = -1;
while (n < 1) {
printf("Enter array size (positive integer): ");
if (scanf("%d", &n) != 1) {
puts("\nERROR: non-numeric");
exit(1);
}
}
Upvotes: 4
Reputation: 94
The error is in this part of your code:
int n,a[n],op;
// int n is not defined as anything so it is a garbage value
// you specify the size of the array to be n
// which allocates an undefined size for the array
Also in your first loop you reassign &a[n]
, which is undefined since it goes beyond the size of the array and even if it were valid it would just reassign a single element, it should be &a[i]
.
to fix it read the value of n before defining array 'a'. The changes i made are down below:
#include<stdio.h>
int main()
{
int n; // change
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n],op; // change
printf("Enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]); // change
}
printf("Select array element to display from 1 to %d\n",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %d\n",a[op-1]);
}
else
{
printf("Invalid Entry\n");
}
return 0;
}
Upvotes: 0