1

I try to create arr[N][N] and I wrote this:

int **arr;
arr = (int**)malloc((strlen(str) - 1) * sizeof(int*));
for (i = 0; i < strlen(str) - 1; i++) {
    arr[i] = (int*)malloc((strlen(str) - 1) * sizeof(int));
}

If in to example the size of str is 6 I need to create arr[5][5], how can I fix it?

user2976686
  • 159
  • 1
  • 1
  • 8

2 Answers2

2

Why wouldn't you just do this (N could be 5):

int **arr;
arr = malloc(N*sizeof(int*));
for (int i = 0; i < N; i++) {
    arr[i] = malloc(N*sizeof(int));
}
Bruce Dean
  • 2,798
  • 2
  • 18
  • 30
1

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Why have this in the loop: `N * sizeof(arr[i][0])`? Seems like a waste of CPU cycles to recalculate it every loop iteration. – Fiddling Bits Dec 01 '13 at 13:40
  • 1
    @Bit Fiddling Code Monkey I take it you are suggesting to create the `size_t len = N * sizeof(arr[i][0]);` before the loop and use `arr[i] = malloc(len);` inside the loop. Should `N` be a constant, the posted code I'd expect a bit faster. Should `N` be a variable, your idea would be faster. In either case, profiling would provide definite results. I'd expect margin differences. – chux - Reinstate Monica Dec 01 '13 at 13:55
  • hi,first thanks!..this is write me error in the line: arr = malloc(N * sizeof(*arr)); – user2976686 Dec 01 '13 at 14:09