Search code examples
cmatrixcharadjacency-matrix

Odd output allocating 2D char Matrix in C


working on a small project and I'm trying to make a 2D array of chars. I've done it with ints before and tried to go off of that example, but it seems like I'm running into an issue that I don't understand.

This is how I'm doing it:

adjMatrix = (char **) malloc(sizeof(char *) * dimensions);

for (int i = 0; i < dimensions; i++)
    adjMatrix[i] = (char *) malloc(sizeof(char) * (dimensions + 2));

for (int i = 0; i < dimensions; i++)
    for (int j = 0; j < (dimensions + 2); j++)
        adjMatrix[i][j] = '0';

Here is my display function:

    for (int i = 0; i < dimensions; i++)
    {
        for (int j = 0; j < (dimensions + 2); j++)
            printf("%s ", &(adjMatrix[i][j]));

        printf("\n");
    }

And this is my output

000000 00000 0000 000 00 0 
000000 00000 0000 000 00 0 
000000 00000 0000 000 00 0 
000000 00000 0000 000 00 0 

Could anyone explain to me why it's showing that way and give any advice as to how to make it just a single '0' in each slot?


Solution

  • Could anyone explain to me why it's showing that way and give any advice as to how to make it just a single '0' in each slot?

    This is, because you advise to print a string and not a single character.

    Change your code to:

    printf("%c ", adjMatrix[i][j]);
    

    Note, adjMatrix[i] points to an array of single characters and an array of characters is a string. Further this is undefined behavior, because you don't 0 terminate the "string".

    &adjMatrix[i][0] is a pointer to '0' '0' '0' '0' '0' '0',
    &adjMatrix[i][1] is a pointer to '0' '0' '0' '0' '0',
    &adjMatrix[i][2] is a pointer to '0' '0' '0' '0',
    ...