Use N
rather than strlen(str) - 1
.
int **arr;
arr = malloc(N * sizeof(*arr));
for (i = 0; i < N; i++) {
arr[i] = malloc(N * sizeof(arr[i][0]));
}
Usually when strlen(str)
comes into play, that allocation size is strlen(str) + 1
(in the for loop only).
From subsequent comments, there is some confusion. Now I assume OP wants to store an array of strings. Assume there are up to N
strings.
#include <stdlib.h>
char **arr;
// See note on casting the results of malloc()
arr = (char **) malloc(N * sizeof(*arr));
for (i = 0; i < N; i++) {
char str[100];
scanf("%99s", str);
size_t siz = strlen(str) + 1;
arr[i] = (char *) malloc(siz);
memcpy(arr[i], buf, siz);
}
Checking the results of malloc()
is a good idea for robust code as in
arr = (char **) malloc(N * sizeof(*arr));
if (arr == NULL) handle_error(); // maybe exit?
Casting note: OP reports twice problems with code that uses a cast-less malloc()
. Not having the cast, with compliant compilers it should not be a problem. But if OP is using a C++ compiler or something non-compliant, casting should fix that issue. With modern C, casting malloc()
results it is tolerable, but frowned upon.