Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass array to function argument?

I have this code:

#include <stdio.h>

void replaceIndexElement (int index, int element);

int main () 
{
    replaceIndexElement(2, 3);
    return 0;
}

void replaceIndexElement (int index, int element) {
    int mainArr[10] = {0, 2, 1000, 6, 9, 11, 43, 8, 123, 87};
    mainArr[index] = element;
    for (int i = 0; i < 10; i++) {
        printf("%d\n", mainArr[i]);
    }
}

I need pass array mainArr to function argument to pass any array and change the element by index.

I have some errors after passing array to argument.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems you mean the following

#include <stdio.h>

int replaceIndexElement( int a[], size_t n, size_t index, int element );

int main ( void ) 
{
    int mainArr[] = { 0, 2, 1000, 6, 9, 11, 43, 8, 123, 87 };
    const size_t N = sizeof( mainArr ) / sizeof( *mainArr );

    replaceIndexElement( mainArr, N, 2, 3 );

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

    return 0;
}

int replaceIndexElement ( int a[], size_t n, size_t index, int element )
{
    int success = index < n;

    if ( success )  a[index] = element;

    return success;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading