【发布时间】:2011-02-28 08:26:35
【问题描述】:
我正在用 C 创建一个动态二维字符数组:
注意:rows 和 columns 是用户输入 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';
}
}
稍后在我的代码中,我尝试覆盖数组中的特定位置:
items[arbitraryRow][arbitraryColumn] = 'S';
但结果是该行/列中的字符现在是“SO”
我做错了什么?
更新: 这就是我打印数组的方式:
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");
}
【问题讨论】:
-
你总是可以使用 char times = (char)malloc(rowscolssizeof(char)); char c = times[j*rows + i];
-
你怎么看他们的?一个字节的内存不能包含两个字符。
-
您是否像这样打印您的内容:
printf("%s", items[arbitraryRow])?还有一个问题:items[arbitraryRow][arbitraryColumn]的内容真的等于'SO'或"SO"吗?我的意思是通常字符常量(用'引用)只包含一个字符。 -
你可以跳过
sizeof(char),因为这是根据定义1 -
你应该使用
%c来打印一个字符。使用%s并传递指针将寻找一个以NULL 结尾的字符串,它可以是SO或者可以包含一些在SO之后的垃圾字符(因为不能保证值为0 的字节存在)