I’m having a real difficult time getting this code to work. I’m trying to pass an array by reference to a function, in order to modify it in that function. Then I need the modifications to be handed back to the original caller function.
I have searched here for a similar problem, but couldn’t find anything that can run successfully like the way I want to do it.
Here’s my code, I would really appreciate any help. Thanks a lot:
#include <stdio.h>
#include <stdlib.h>
#define SIZE_OF_VALUES 5
#define SIZE_OF_STRING 100
void set_values(char **values);
void set_values(char **values)
{
*values = malloc(sizeof(char)*SIZE_OF_VALUES);
for (int i = 0; i < (sizeof(char)*SIZE_OF_VALUES); i++) {
values[i] = malloc(sizeof(char)*SIZE_OF_STRING);
values[i] = "Hello";
//puts(values[i]); //It works fine here.
}
}
int main (int argc, const char * argv[])
{
char *values;
set_values(&values);
for (int i = 0; i < (sizeof(char)*SIZE_OF_VALUES); i++) {
puts(values[i]); //It does not work!
}
return 0;
}
There are several problems with your code:
You should have three-level pointers –
void set_values(char ***values), read it as a “a reference (first*) to an array (second*) ofchar*(third*)”Each element in
*valuesshould be a pointer (char*) notchar, so you need:You are leaking memory, first mallocing then assigning literal, and additionally not dereferencing
values, you need either:or
or
In your
main, you should declarechar **values;as it is a pointer to an array ofchar*(character string/array).In you loop you are incorrectly multiplying indices by
sizeof, index is counted in elements not in bytes. Thus, you need:Don’t forget to free the memory at the end.