使用 C 覆盖数组中的字符
我正在 C 中创建一个动态二维字符数组:
注意:行
和列
是用户输入整数
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");
}
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");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不是存储字符串,而是存储字符,所以你只能读取一个字符,所以那就是 S
我怀疑下一个字符是 O,所以当你将它视为字符串时,你会得到 SO
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
您正在存储字符并读取字符串。尝试从数组中读回字符。
将您的代码更改为:
You are storing characters and reading strings. Try reading character back from the Array.
Change your code to: