简体   繁体   中英

Initialising an int array in an if statement and using externally

New to C here and would appreciate if I could get some pointers.

I'm trying to initialise an array inside an if statement, and then print the values of the array externally - but I know the scope will be lost after the if block ends. I've tried creating the array with pointers. The reason I'm doing it inside the if statement is because the size of the array depends on a value calculated during runtime.

Eg:

void createArray() {

    int userInput;
    printf("%s\n", "Please enter a value:");
    scanf("%d\n", userInput);

    if (userInput > 10) {
       int array[userInput];
    }

    int i;
    for (i = 0; i < userInput; i++) {
       array[i] = i;
    }
}

int i;
for (i = 0; i < sizeof(array)/sizeof(array[0]); i++) {
  printf("%d\n", array[i]);
}

However because the array is declared inside a method, I obviously lose scope of it when it comes to the final for loop to print - thus an error occurs. I've tried creating a pointer variable int *array as a global variable, and inside the if statement, just staying array = int[10] but obviously this won't work.

This isn't my exact code, I've recreated a minimal example that shows my error so some syntax may be wrong here - apologies for that.

Any help would be appreciated.

One question you have to consider in your code is what happens if userInput is less than or equal to 10? You iterate over userInput elements of an array that was not declared.

One simple way of handling this is to make a large array at the beginning of your function and then use just the first userInput elements of it. This approach has obviously its limitations (eg userInput can't be larger than the size of the array, and you should make sure it won't be, otherwise bad things may happen), but is simple.

Another approach involves using dynamic memory allocation. This is done by using the malloc function:

int *array = malloc(100 * sizeof(int));

The code above allocates memory for 100 ints, basically creating an array of 100 elements. Then, you can use the array as usual. But, make sure you free it after you're done:

free(array);

Note that using this approach you'd need to declare the pointer first:

int *array;
if (userInput > 10) {
   array = malloc(userInput * sizeof(int));
}

Below you can find a small proof of concept program. Note that instead of a global variable, the pointer value can be returned from the alloc function.

#include <stdio.h>
#include <stdlib.h>

int *arr;

void alloc() {
    arr = malloc(10 * sizeof(int));
}

void assign() {
    for (int i = 0; i < 10; i++)
        arr[i] = i + i;
}

void print() {
    for (int i = 0; i < 10; i++)
        printf("%d\n", arr[i]);
}


int main(int argc, char *argv[])
{
    alloc();
    assign();
    print();
    free(arr);
    return 0;
}

This allocates an array of int to the pointer intary. The pointer may be passed to other functions from main() . In main, userInput stores the number of int allocated.

#include <stdio.h>
#include <stdlib.h>

int *createArray( int *userInput);

int main( int argc, char *argv[])
{

    int i;
    int userInput = 0;
    int *intary = NULL;

    if ( ( intary = createArray ( &userInput)) != NULL ) {

        for (i = 0; i < userInput; i++) {
            intary[i] = i;
            printf ( "%d\n", intary[i]);
        }

        free ( intary);
    }
    return 0;
}

int *createArray( int *userInput) {

    int *array = NULL;

    printf("%s\n", "Please enter a value:");
    scanf("%d", userInput);

    if ( *userInput > 10) {
        if ( ( array = malloc ( *userInput * sizeof ( int))) == NULL) {
            printf ( "could not allocate memory\n");
            *userInput = 0;
            return NULL;
        }
    }
    else {
        *userInput = 0;
        return NULL;
    }

    return array;
}

You don't need some pointers, just one, (int* arr) and malloc(),a dynamic memory allocation function.

Note: You shouldn't use "array" as a variable name as it may create problems. So we'll name our variable arr.

If you're unfamiliar with it, i will explain the code too.

  1. First add #include <stdlib.h> header file, which contains malloc().

  2. Then declare a pointer of type int int* arr , we have named it arr in the createArray() scope.

  3. We'll allocate the space required in the if condition with malloc() function, like :

     void createArray() { int userInput; int* arr; // declare arr pointer printf("%s\\n", "Please enter a value:"); scanf("%d\\n", userInput); if (userInput > 10) { arr = (int*) malloc ( userInput * sizeof(int) ); // explained below } int i; for (i = 0; i < userInput; i++) { arr[i] = i; } } free(arr) // don't forget to free after using 

[NOTE] This code is untested.

arr = (int*) malloc ( userInput * sizeof(int) );
This line may seem cryptic at first, but what it does is pretty simple , it allocates some memory dynamically on the heap.
The size of this memory is given by 'userInput * sizeof(int)', sizeof() function specifies the size of int on the given machine multiplied by userInput by the user,
Then, it is typecasted to int* type so that we can store the address in our int* type pointer arr.

[UPDATE] you can use arr = malloc ( userInput * sizeof(int) ); instead as suggested in comments, here is why Do I cast the result of malloc?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM