Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>char *array[3][2] is nothing but a two dimensional array of pointers. Hence you need the storage space of 3*2*sizeof(char *) to store the pointers.</p> <p>As you mentioned, the pointers are actually pointing to zero-terminated strings and you may like the strings to be malloc'ed as well. Assuming the total length of all the strings to be N (including zero-termination), the storage space needed is (3*2*sizeof(char *) + N).</p> <p>Allocate memory for the above mentioned size and the copy the strings yourselves as below.</p> <p>In the following code, we assume that the number of columns (2) is a constant</p> <pre><code>char *(*dst)[2] = (char *(*)[2]) malloc(3*2*sizeof(char *) + N); char * s = ((char *) dst) + (3*2*sizeof(char *)); for (i = 0; i &lt; 3; i++) { for (j = 0; j &lt; 2; j++) { strcpy(s, src[i][j]); dst[i][j] = s; s += strlen(s)+1; } } </code></pre> <p>NOTE: In the above code, 'dst' is a pointer that points to the first row of the 2D array of char *.</p> <p>If the number of columns is not constant, the syntax changes a bit, but the storage size is the same.</p> <pre><code>char **dst = (char **) malloc(3*2*sizeof(char *) + N); char * s = ((char *) dst) + (3*2*sizeof(char *)); for (i = 0; i &lt; 3; i++) { for (j = 0; j &lt; 2; j++) { strcpy(s, src[i][j]); dst[i*2 + j] = s; /* 2 is the number of columns */ s += strlen(s)+1; } } </code></pre> <p>NOTE: Here 'dst' is a pointer that points to the first element of 1D array of char * and the 2D indexing is done manually.</p> <p>The above examples assume that the string lengths will not change after allocation. If the strings can change at any point in time after allocation, then it is better to allocate for each string separately.</p>
    singulars
    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.
    1. VO
      singulars
      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