I've got a problem when dealing with one- and two-dimensional dynamically allocated arrays in C. I have found similar questions, however none of them helped me so I'm asking a new one.
- C and pointer in a function - changes do not save
- C implementention of strcpy does not change variable value
- Changing address contained by pointer using function
Here is my problem. With the function below I want to add a new element into a two dimensional char array. Size is not the problem, I increment somewhere outside.
void addElem(char ***tabs, int size, char *new) {
*tabs[size] = (char*)malloc(sizeof(char)*strlen(new));
*tabs[size] = new;
*tabs = (char **)realloc(*tabs, size * sizeof(char *));
}
In the code the function is called this way:
int i;
char *tmp;
char **array = (char **)malloc(sizeof(char *));
//some stuff, also initializing i and tmp
addElem(&array, i, tmp);
The problem is that the function even if allocates the data, it does not save any data there (for example, strcmp gives SIGSEGV using **array). When debugging similar functions (managing one-dim int arrays), I found out that they in fact work properly inside these functions, the data is just not saved after returning.
I tried to show as small amount of code as possible, but if it helps here is the full code (with addElem function renamed to dodajDoTablicySlow). Thanks.