Generally, if you don't want brackets, you don't want to use an array. You're looking for pointers here. The simplest way to allocate the required bytes of memory is to use malloc()
, and then you can use *(p + i)
like syntax to get data from the user or display the output.
Here's a demo:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // Max number of elements (in words of an array)
int main(void) {
// Declaration and initialization of the required pointer
int *p = (int *)malloc(sizeof(int) * MAX);
for (int i = 0; i < MAX; i++) {
printf("Enter %dth position value: ", i);
// Verification of user input
if (scanf("%d", (p + i)) != 1) { // equivalent to &*(p + i)
puts("Incorrect value. Quitting...");
return 1;
}
}
for (int i = 0; i < MAX; i++)
printf("%d
", *(p + i)); // dereference to (p + i) used here
free(p); // Free the memory before exit, unnecessary here
// but good practice
return 0;
}
Output of the sample code will be similar (notice the input as well):
Enter 0th position value: 5
Enter 1th position value: 3 // (correct to 1st)
Enter 2th position value: 8 // (correct to 2nd)
Enter 3th position value: 6 // (correct to 3rd)
Enter 4th position value: 3
5
3
8
6
3
Note: This doesn't mean the arrays are bad.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…