Home > Blockchain >  In C - Can I initialize an array (and set the size) from within a function?
In C - Can I initialize an array (and set the size) from within a function?

Time:03-28

I am trying to pass a pointer to a funcion, and in that function create an array, and set the passed pointer to that array.

What I'm trying to do is create an array inside the function and then use that array outside the funcion.

void createArray(int *myPointer)
{
    int intArray[20];

    *myPointer = &intArray[0]; // This line gets error:
                               // assignment makes integer from pointer without a cast [-Wint-conversion]

    for (int i = 0; i < 20; i  )
    {
        intArray[i] = i   10;
    }
}

int main(void)

{
    int *intPointer;
    createArray(&intPointer);
    for (int i = 0; i < 20; i  )
    {
        printf("%d : %d \n", i, intPointer[i]);
    }
    return 0;
}

CodePudding user response:

You meant to use

void createArray(int **myPointer)

That will resolve the two type errors.

But that will make main's pointer point to a variable that no longer exists after createArray returns. That's bad. And that's why you have to use malloc instead of automatic storage.

void createArray( int **myPointer ) {
    int *intArray = malloc( 20 * sizeof(int) );

    *myPointer = intArray;  // Same as `&intArray[0]`
    if ( !intArray )
       return;

    for ( int i = 0; i < 20; i   )
        intArray[i] = i   10;
}

int main(void) {
    int *intPointer;
    createArray(&intPointer);
    if ( intPointer ) {
       perror( NULL );
       exit( 1 );
    }

    for (int i = 0; i < 20; i  )
        printf( "%d: %d\n", i, intPointer[i] );

    return 0;
}
  • Related