Issues
char** arr = malloc( sizeof(char*) + n ); allocates (most likely) 24 bytes which can only store (most likely) six char *.
You don't need to try offset the address (*(arr + sizeof(char*) * i) = base;) by the base type. The offset is automatically adjusted by the sizeof the base type.
The following changes must be made:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int n = 20;
char **arr = malloc(sizeof(char *) * n);
char *base = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0; i < n; i++)
arr[i] = base;
for(int i = 0; i < n; i++)
printf("%d: %s\n", i, arr[i]);
return 0;
}
The preceding uses array notation. You can also use pointer notation if you'd like. Change arr[i] to *(arr + i).
Output
$ gcc main.c -o main.exe; ./main.exe
0: abcdefghijklmnopqrstuvwxyz
1: abcdefghijklmnopqrstuvwxyz
2: abcdefghijklmnopqrstuvwxyz
3: abcdefghijklmnopqrstuvwxyz
4: abcdefghijklmnopqrstuvwxyz
5: abcdefghijklmnopqrstuvwxyz
6: abcdefghijklmnopqrstuvwxyz
7: abcdefghijklmnopqrstuvwxyz
8: abcdefghijklmnopqrstuvwxyz
9: abcdefghijklmnopqrstuvwxyz
10: abcdefghijklmnopqrstuvwxyz
11: abcdefghijklmnopqrstuvwxyz
12: abcdefghijklmnopqrstuvwxyz
13: abcdefghijklmnopqrstuvwxyz
14: abcdefghijklmnopqrstuvwxyz
15: abcdefghijklmnopqrstuvwxyz
16: abcdefghijklmnopqrstuvwxyz
17: abcdefghijklmnopqrstuvwxyz
18: abcdefghijklmnopqrstuvwxyz
19: abcdefghijklmnopqrstuvwxyz
As recommended by Swordfish you should use the const qualifier on arr and base:
const char **arr = malloc(sizeof(char *) * n);
const char * const base = "abcdefghijklmnopqrstuvwxyz";
In this way:
arr cannot change (without a warning/error) pointed to chars.
- Neither the address of
base nor the pointed to chars can be changed (without a warning/error).
Thanks
To Tim Randall for catching a math error.
sizeof(char*) + nis a problemarr[i]is*(arr + i), not*(arr + sizeof(char*) * i). You have to use thesizeofoperator only with the functions that operate on raw data viavoid *pointers. In the pointer arithmetic above, the size of one element is inferred fromarr's type.arr[0 ... 19]point to.sizeof(char*) + nis actually a paste mistake