0

How do we pass an char array as an argument to a callback? When I try to code something like:

void caller(void (*function)(char*), char* string)
{
     function(string);
}

void function(char* string)
{
     string[0]=data0;
     string[1]=data1;
     string[2]=data2;
}

void principal()
{
     char* str={0};
     caller(&function, str);
}

in the debugger watchlist, the string argument behaves like a common pointer (not an array) and the char array does not get populated with data at all. The function "principal" gets called in the main() when certain conditions are met.

  • Welcome to Stack Overflow, take a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Yeheshuah Jun 01 '21 at 01:37
  • Also possible duplicate. https://stackoverflow.com/questions/6567742/passing-an-array-as-an-argument-to-a-function-in-c – Yeheshuah Jun 01 '21 at 01:39
  • Welcome to SO. What is this supposed to do? `char* str={0};` Don't you want to provide some memory for our callback function? Also: Your string argument **is** a pointer. Even if it was an array in the parameter list, it would decay to a plain pointer. – Gerhardh Jun 01 '21 at 05:38
  • Which "char array" are you talking about? There is no array in your code. – Gerhardh Jun 01 '21 at 05:40
  • Does this answer your question? [Passing an array as an argument to a function in C](https://stackoverflow.com/questions/6567742/passing-an-array-as-an-argument-to-a-function-in-c) – the busybee Jun 01 '21 at 06:49

1 Answers1

0

You have not allocated any memory for str in principal() and your code have a big vulnerability about buffer overflow.

So I fixed your code by changing how str is declared and to add a size argument to function() and check it so that there is no overflow possible. For the rest, I kept the code as close as possible to what you showed:

char data0 = 'A';
char data1 = 'B';
char data2 = 'C';

void caller(void (*function)(char*, int size), char* string, int size)
{
    function(string, size);
}

void function(char* string, int size)
{
    if (size >= 3) {
        string[0] = data0;
        string[1] = data1;
        string[2] = data2;
    }
}

void principal()
{
    char str[] = { 0, 0, 0 };
    caller(&function, str, sizeof(str));
}
fpiette
  • 11,983
  • 1
  • 24
  • 46