Reputation: 67
I am creating a 2D array using malloc and when I iterate through the array there are characters and symbols that I do not want in there. Shouldn't the array be completely empty?
I have tried to assign the null character to the beginning of each row but that doesn't change anything.
char **structure;
structure = malloc(sizeof *structure * 2);
if (structure) {
for (size_t i = 0; i < 2; i++) {
structure[i] = malloc(sizeof *structure[i] * 20);
structure[i][0] = '\0';
}
}
for (int i = 0; i <= 2; i++) {
for (int j = 0; j < 20; j++) {
printf("%c ", structure[i][j]);
}
printf("\n");
}
I expected the output to just be blank spaces but this is what appeared:
Z Ñ P Ñ l L O
Z Ñ P Ñ N U M B
Upvotes: 3
Views: 1255
Reputation: 144695
You are not really allocating a 2D array of char
, but an array of 2 pointers to arrays of 20 char
. It is much simpler to allocate a true 2D array:
// allocate a 2D array and initialize it to null bytes
char (*structure)[20] = calloc(sizeof(*structure), 2);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 20; j++) {
printf("%02X ", structure[i][j]);
}
printf("\n");
}
Output:
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Upvotes: 1
Reputation: 39
When you are allocating memory the data inside the memory is undefined. the malloc function just giving you the memory. if you want the memory to be initialized to 0 you can always use the standard calloc function. If you want to initialize it after allocation you can always use the memset function. in your case
memset(structure, 0, (sizeof *structure) * 2)
Upvotes: 1
Reputation: 908
As you are accessing each character you must clear all position explicitly to get your desired output.
char **structure;
structure = (char**)malloc( (sizeof *structure) * 2 );
if (structure)
{
for(size_t i = 0; i < 2; i++){
// structure[i];
structure[i] =(char *) malloc( sizeof *structure[i] * 20 );
for(int j=0; j<20; j++)
structure[i][j] = '\0';
}
}
for(int i = 0; i < 2; i++){ //you can not access position i==2
for(int j = 0; j < 20; j++)
{
printf("%c ", structure[i][j]);
}
printf("\n");
}
You can also use printf("%s", structure[i]) to make it work with your current code. it will work because you have made first position of both strings NULL('\0').So printf function will terminate for both character arrays without printing anything. But remember, other position than the first one of both arrays will contain garbage value.
Upvotes: 3
Reputation: 1305
You should use the calloc
function; this is what I often use. It does the same work as malloc()
but it initializes all allocated bits with 0
.
Upvotes: 6