#include <stdio.h>
#include <stdlib.h>
void populateArray(char* line, char** cmd){
printf("INPUT LINE: %s\n", line);
char * token = strtok (line, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'cmd' */
while (token) {
*cmd = realloc (*cmd, sizeof (char*) * ++n_spaces);
if (*cmd == NULL)
exit (-1); /* memory allocation failed */
*cmd[n_spaces-1] = token;
token = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
*cmd = realloc (*cmd, sizeof (char*) * (n_spaces+1));
*cmd[n_spaces] = 0;
/* print the cmd */
for (i = 0; i < (n_spaces+1); ++i)
printf ("cmd[%d] = %s\n", i, cmd[i]);
}
int main (int argc, char* argv[])
{
char *cmd1 = NULL;
char * line = "ls -l";
populateArray(line, &cmd1);
}
I know that C is pass by value but is there anyway to emulate it to pass by reference? I need to pass cmd1 to populateArray(char* line, char** cmd) as a reference. I did some research and to pass by reference in C, it seem like I need to do something like this: I tried but still cant make it work for the array pointer.
void byreference_func(int* n){
*n = 20;
}
int main(int argc, char *argv[])
{
int i = 10;
printf("before the call the value of i is %d\n", i);
byreference_func(&i);
printf("after the call the value of i is %d\n", i);
return 0;
}
EDIT: Error code
anon@turing:~/csce3613/assign3$ gcc gg.c
gg.c: In function âpopulateArrayâ:
gg.c:6:24: warning: initialization makes pointer from integer without a cast [enabled by default]
gg.c:17:23: warning: assignment makes integer from pointer without a cast [enabled by default]
gg.c:19:13: warning: assignment makes pointer from integer without a cast [enabled by default]
anon@turing:~/csce3613/assign3$ ./a.out
INPUT LINE: ls -l
Segmentation fault (core dumped)