Note that there are some explanatory texts on larger screens.

plurals
  1. PO1 array into 2 string arrays with malloc problems and pass by ref
    primarykey
    data
    text
    <p>HI I am working on something for one of my classes.. Im</p> <p>trying to take in this array of strings, break it up into 2 arrays and return back to the caller.. I am new to C, so if you could help, be very helpful, thanks... Right now I get a compile warning, and then a Segfault when I run it. </p> <p>I've been trying many things such as changing the method signature by adding *'s and passing by &amp;.. but it seems not to work..</p> <p>I prolly am doing a bunch of stuff wrong... pls help.. what I want is to return 2 arrays back to main() with pList[0] = "less"</p> <p>and cList[0] = "ls" and cList[1] = "-t" ...from the function by passing in by reference..</p> <p>heres my code so far</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; void makeLists(char **args, char*** parentList, char*** childList, int *childEnd, int *parentEnd) { int i; int foundPipeAt = 0; int total = 0; for(i = 0; i &lt; 4; i++) { total++; if (strcmp(args[i], "|") == 0) { foundPipeAt = i; } } *parentList = malloc((foundPipeAt-1) * sizeof(char*)); *childList = malloc((total-(foundPipeAt)) * sizeof(char*)); printf("foundPipe %d\n", foundPipeAt); for (i = 0 ; i &lt; foundPipeAt ; i++ ) { *parentList[i] = (char *) malloc( (strlen(args[i])+1) * sizeof(char)); *parentList[i] = args[i]; printf("Parent List: %s\n", *parentList[i]); } // Set values for Parent end *parentEnd = foundPipeAt-1; *childEnd = total-foundPipeAt; int k=0; for (i = foundPipeAt+1 ; i &lt; total ; i++ ) { *childList[k] = malloc((strlen(args[i])+1) * sizeof(char)); *childList[k] = args[i]; // This prints correctly... printf("Child List: %s\n", *childList[k]); k++; } } main() { int i; char *args[4]; args[0] = "ls"; args[1] = "-t"; args[2] = "|"; args[3] = "less"; char **pList; char **cList; int parentEnd, childEnd; makeLists(args, &amp;pList, &amp;cList, &amp;childEnd, &amp;parentEnd); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload