The only serious problem I see in your code is that you are casting the returned value of malloc(3)
, and probably you have forgotten to #include <stdlib.h>
also (this is a dangerous cocktail), and this way, you are destroying the returned value of the call with the cast you put before malloc(3)
. Let me explain:
- First, you have (or haven't, but I have to guess) a 64bit architecture (as it is common today) and pointers are 64bit wide in your system, while
int
integers are 32bit wide.
- You have probably forgotten to
#include <stdlib.h>
in your code (which is something I have to guess also), so the compiler is assuming that malloc(3)
is actually a function returning int
(this is legacy in C, if you don't provide a prototype for a function external to the compilation unit), so the compiler is generating code to get just a 32 bit value from the malloc(3)
function, and not the 64bit pointer that (probably, but I have to guess also) malloc(3)
actually returns.
- You are casting that
int
32bit value (already incorrect) to a 64bit pointer (far more incorrect, but I have to guess...), making any warning about type conversions between integer values and pointers to dissapear, and be silenced when you put the cast (the compiler assumes that, as a wise programmer you are, you have put the cast there on purpose, and that you know what you are doing)
- The first (undefined behaviour) returned value is being (undefined behaviour) just cut to 32 bit, and then converted (from
int
to char *
, with more undefined behaviour) to be used in your code. This makes the original pointer returned from malloc(3)
to be completely different value when reinterpreted and cast to (char *)
. This makes your pointers to point to a different place, and break your program on execution.
Your code should be something like (again, a snippet has to be used, as your code is not complete):
#include <stdlib.h> /* for malloc() */
/* ... */
char *arr[rownum2];
for (i = 0; i < rownum2; i++) {
arr[i] = malloc(colnum); /* sizeof(char) is always 1 */
I need finally to do you a recommendation:
Please, read (and follow) the how to create a minimal, verifiable example page, as your probable missing #include
error, is something I had to guess.... Posting snippets of code makes many times your mistakes to go away, and we have to guess what can be happening here. This is the most important thing you have to learn from this answer. Post complete, compilable and verifiable code (that is, code that you can check fails, before posting, not a snippet you selected where you guess the problem can be). The code you posted does allow nobody to verify why it can be failing, because it must be completed (and repaired, probably) to make it executable.