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

void array_tester(int *array);

int main(int argc,char *argv[])
{   
    int test[] = {1,1,1,1};
    int print;
    for(print = 0; print < sizeof(test) / sizeof(int); print++)
    {
        printf("%d\n",test[print] );
    }

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

    return EXIT_SUCCESS;
}


void array_tester(int array[])
{   
    int i ;
    for(i = 0; i < sizeof(array) / sizeof(int); i++)
    {
        array[i] = i;
    } 
}

The problem is I want to modify the the array in the array_tester function but I'm unable to do so. What do I use inside sizeof()?

1 Answer 1

5

You have to manually pass the information about the size of the array.

void array_tester( int* array , int size ) ;

And then call it:

array_tester( test , sizeof(test)/sizeof(*test) ) ;

The reason behind this is that array passed to a function will decay to a pointer and the sizeof will return the size of pointer not the original array.

Sign up to request clarification or add additional context in comments.

1 Comment

Well explained, +1 in particular for explaining how the replaced solution differs from the original one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.