Search code examples
carraysfunctionpointersunsigned-char

C Program: Update unsigned char pointer array with function


I have a function to update an unsigned char* and cannot find where my bug is. I'm not sure if I need to allocate memory, or if I am pointing to the wrong memory space somewhere. I tried to follow a similar structure as posted here, but have not had success with an unsigned char.

My code so far:

#include <stdio.h>

void changeArray(unsigned char **arr)
{
    unsigned char ptr[3] = {100, 101, 102};
    *arr = ptr;
    printf("%d\n", **(arr+0)); // This prints out the correct value of 100
}

int main(int argc, const char* argv[])
{
    int i = 0;
    unsigned char *blah;
    unsigned char ptr2[3] = {103, 104, 105};
    blah = ptr2;
    printf("Blah is: \n");
    for (i = 0; i < 3; i++) {
        printf("%d,",*(blah+i)); //This prints out 103,104,105
    }
    changeArray(&blah);
    printf("Blah is now: \n");
    for (i = 0; i < 3; i++) {
        printf("%d,", *(blah +i)); //This prints out 0,0,0
    }
    return 0;
}

Any help in determining how to properly access the values set in the changeArray() function would be greatly appreciated.


Solution

  • With this *arr = ptr; you are storing a pointer to a variable with automatic storage duration. The behaviour undefined.

    You can dynamically allocate and return a pointer that way:

    void changeArray(unsigned char **arr)
    {
        unsigned char ptr[3] = {100, 101, 102};
        unsigned char *p = malloc(sizeof ptr); 
        memcpy(p, ptr, sizeof ptr);
        *arr = p;
        printf("%d\n", **(arr+0)); // This prints out the correct value of 100
    }
    

    You should also do error checking if malloc failed and remember to free the allocated memory after use in main.