You need to understand the mechanism of how an array
is passed to a function in C programming language. When you pass an array to a function in C, pointer (address) to first element of the array is passed to the function and since you have a reference to it, you can modify the content of the array in the function (but you can't change the memory location to which array is pointing). I recommend to have a look at this question.
The program below has two functions. rightFunc
function is a simple and correct approach to achieve what you have been trying to do. However, I have provided func
which shows the way of passing pointer (or reference) to an array of pointers.
#include <stdio.h>
#define SIZE 100
void rightFunc(char *array[], char *b)
{
array[0] = b;
}
void func(char *(*array)[], char *b)
{
(*array)[0] = b;
}
int main(int argc, char *argv[])
{
char *array_in_main[SIZE];
char b_in_main = 'b';
func(&array_in_main, &b_in_main);
printf("Character is %c\r\n", *array_in_main[0]);
b_in_main = 'c';
rightFunc(array_in_main, &b_in_main);
printf("Character is %c\r\n", *array_in_main[0]);
return 0;
}
I would like to point out one error in your program. You can get address of local variable (automatic storage class
) but that address will not be valid outside the function (when function has exited). To rectify the issue in your program, I have modified the functions to take pointer to char
in your program.