What am I doing wrong here with passing a char array to a function and in the function giving each index memory (using malloc()), then inserting something from the keyboard using gets().
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
void test(char *arr[]);
int main(){
char *arr[2];//2 is the rows
/* arr[0] = malloc(80);//This commented code works
arr[1] = malloc(80);
strcpy(arr[0], "hey");
strcpy(arr[1], "whats up");
*/
test(*arr);
printf("in array[0]: %s", arr[0]);
printf("in array[1]: %s", arr[1]);
return 0;
}
void test(char *arr[]){
int index;
char *input = malloc(80);
for(index = 0; index < 2; index++){
arr[index] = malloc(80);
gets(input);
strcpy(arr[index], input);
//arr[0] = input;
}
}
Just a very basic program which for some reason I am having trouble with. Also one more question When I declare an array what is the difference between these forms
char *array
as oppose to
char *array[size]
or
char **array
Thanks,
Kevin
You declare
arraschar *arr[2]. You then pass in*arr, which has typechar*to test. But test expects achar *[]. So that won’t work. You should simply pass inarras it is, i.e.test(arr).char * arrayis a pointer to character, typically used to point to the first character in an array of characters, i.e. a string.char **arrayis a pointer to pointer to character. Typically used to represent an array of strings.char *array[size]is mostly equivalent to the one above, but it unlike, that one, the top-level pointer is already pointing at a valid array, so the array does not need to bemalloced.By the way, your
testfunction could be simplified a bit: thestrcopyis unneccessary.