'I want user input of array elements and the size of an array as well but, it shows me compilation error what am i missing
I want user input of array elements and the size of an array as well but, it shows me a compilation error what am i missing
#include<stdio.h>
#include<conio.h>
void main(){
int i,x,j;
int index = 1;
int arr[index]; // this is the place error shows up
/* error says constant expression required*/
scanf("enter the number of elements: %d",&index);
clrscr();
for(i=0;i<index;i++){
printf("Enter element of index no %d",i+1);
scanf("%d",&x);
arr[i] = x;
}
for(j=0;j<index;j++){
printf("\n %d ",arr[j]);
}
}
Solution 1:[1]
- Your array
arris sized to one element, changing index after the fact does not adjust the size. In other words, readindex, then declarearr. - You try to use
scanfto print a prompt, but it doesn't work that way. You need to useprintf()to write out the prompt. This was actually was caused the premature exit on my system
Other bonus feedback:
conio.handclrscr()are windows specific, I believe, so I left it out as I could not test it.- Minimized the scope of variables, and eliminated
xas you can just read directly intoarr[i] - Used
unsignedinstead ofintwhen you don't want negative numbers. - Formatted code for readability.
main()by definition returns anintso changed it accordingly to resolve the warning withvoid main() { ...}.
Didn't fix:
- Check the return value from
scanf, mainly, because I didn't know behavior you want. - Check that
indexis reasonable sized. Variable length arrays (VLA) are dangerous as they will blow your stack if your array is too large. Stack size is OS specific and at least on Linux it's user configurable. Personally, I don't use VLA in my code and if I cannot statically allocate an array then I use heap allocation viamallocand friends. - You use name
indexfor the number of elements you read. That term is normally used for loop variable likeihere that indexed into an array. I suggest you renameindexton,len, orsize.
#include <stdio.h>
int main() {
unsigned index;
printf("enter the number of elements: ");
scanf("%u", &index);
int arr[index];
for(unsigned i=0; i<index; i++) {
printf("Enter element of index no %u: ", i+1);
scanf("%d", &arr[i]);
}
for(unsigned i=0; i<index; i++) {
printf("\n %d ", arr[i]);
}
return 0;
}
Example session:
enter the number of elements: 3
Enter element of index no 1: 0
Enter element of index no 2: 1
Enter element of index no 3: 2
0
1
2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
