开发者

Overwrite character in an array using C

开发者 https://www.devze.com 2023-02-14 08:01 出处:网络
I\'m creating a dynamic 2d character array in C: Note: rows and columns are user input integers char** items;

I'm creating a dynamic 2d character array in C:

Note: rows and columns are user input integers

char** items;
items = (char**)malloc(rows * sizeof(char*));
int i;
for(i = 0; i开发者_开发百科 < rows; i++)
{
    items[i] = (char*)malloc(columns * sizeof(char));
}

int j;
for(i = 0; i < rows; i++)
{
    for(j = 0; j < columns; j++)
    {
        items[i][j] = 'O';
    }
}

Later in my code, I attempt to overwrite a specific location in the array:

items[arbitraryRow][arbitraryColumn] = 'S';

But the result is that the characters in that row/column are now 'SO'

What am I doing wrong?

Update: This is how I'm printing the array:

int i;
for(i = 0; i < rows; i++)
{
    printf("[");
    int j;
    for(j = 0; j < columns; j++)
    {
        printf("'%s'", &items[i][j]);
        if(j != columns - 1)
            printf(", ");
    }
    printf("]");
    printf("\n");
}


You're not storing strings you're storing characters so all you can read is one character so that'd be the S

My suspision is that the next character is an O so when you look at it as a string you get SO

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


You are storing characters and reading strings. Try reading character back from the Array.

Change your code to:

int i; 
for(i = 0; i < rows; i++) 
{
     printf("[");
     int j;
     for(j = 0; j < columns; j++)
     {
         printf("'%c'", items[i][j]);
         if(j != columns - 1)
             printf(", ");
     }
     printf("]");
     printf("\n");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消