Passing Array as a function argument and setting element values

advertisements

So the solution to this problem I think is fairly simple but I must be missing something. All I want to do is pass an array to a function and then set the arrays elements values in the function to then use in the global scope.

int setArray(char* myArray) {
    char localArray[9] = "abcdefghi";

    for (int i = 0; i < 10; i++){
       myArray[i] = localArray[i];
       printf("myArray: %c\n", myArray[i]);
    }
    return(0);
};

int main(int argc, char* argv[])
{
    char* globalArray = NULL;

    setArray(globalArray);
    printf("globalArray: %s\n", globalArray);
    return(0);
};

The above code just crashes. at one point I had it working where I could set the globalArray in the function and print out its values but when I printed out the values in main() it was null.

I believe the issue lies with not setting up the pointer correctly and passing it, but I am not sure

any help would be greatly appreciated. thanks.


The pointer globalArray doesn't point to a valid memory location. You need to allocate memory and store that address in globalArray using malloc, calloc etc.

You can allocate memory in main() or in setArray() function as dynamic memory allocation uses heap which is accessible to all the functions even after setArray has exited.

So correct code could be:

char* globalArray = malloc(10 * sizeof(char));
if(!globalArray)
{
    printf("Memory could not be allocated!\n");
    exit(1);
}

setArray(globalArray);
...


Also You haven't copied \0 byte to myArray in function setArray()

After the for loop you need myArray[i] = '\0';


Also you have char localArray[9] = "abcdefghi"; in your code.

Here localArray is not a valid c string as it doesn't contain terminating '\0' character. Though it doesn't poise any problem for now but if you happen to print/alter localArray as string then it'll lead to invalid memory access (SegFault)

So to avoid that use

`char localArray[] = "abcdefghi";`

instead of

`char localArray[9] = "abcdefghi";`