KEEP IN MIND I WROTE THIS CODE IN HERE TO SIMPLIFY MY QUESTION, PLEASE IGNORE MINOR MISTAKES IF THERE ARE ANY, MY PROBLEM FOCUSES ON MANIPULATING AN ARRAY OUTSIDE OF A FUNCTION BY USING IT'S POINTER.
I create a static array like this
char *array[size1][size2];
For the purposes of my example size1 = 3 and size2 = 6.
Then I use a function to pass the pointer of the array, and allocate strings to it.
int counter = 0;
void somefunction(char *a, char *b, int size1){
while(counter<size1){
//do some stuff to a
strcpy(b+counter, a);
counter++;
printf("Adding %s to pos %i RESULT: %s\n",a,counter,b+counter);
}
}
This works nicely and the output is correct (when outputting array b in the function), but it does not actually effect the array[] outside of the function. If I use
somefunction(a,array,size1);
The output will be correct, but the actual array outside of the function (array[]) will output gibberish random memory.
I output it like this:
for(int i=0;i<size1;i++){
printf("%s\n",array[i]);
}
So what am i doing wrong here? I thought the array when passed to a function decays into a pointer to the first element (and therefore that array), but that doesn't seem to be the case. What am I doing wrong? How do I manipulate the array outside of the function by passing it's pointer?
Thanks!
&array[0][0]&array[0][0]is a pointer to a pointer. Passing it to a function expecting achar *is invalid.char* []. When you want an array of pointers to strings you would declare it aschar* array [size];but then you must allocate memory for the strings elsewhere. So what are you actually trying to do here...?