Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a 2D char array completely empty?

Tags:

c

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
like image 918
jpr Avatar asked Dec 21 '25 21:12

jpr


2 Answers

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.

calloc documentation

like image 160
Arnaud Peralta Avatar answered Dec 24 '25 16:12

Arnaud Peralta


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.

like image 20
priojeet priyom Avatar answered Dec 24 '25 18:12

priojeet priyom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!