Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

c - Initializing array of integers without using square [] brackets

I was trying to initialize an array of int in c without the use of [] brackets. As far as I know, int A[n] is equivalent to int *(a+n). I tried initializing the array like this. However, it is not working.

When is this notation, i.e int *(a+n) used, and how can we initialize, scanf and print without using the square brackets?

question from:https://stackoverflow.com/questions/65855737/initializing-array-of-integers-without-using-square-brackets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...