我是编程新手。我写了这个简单的代码来删除二维数组中的一行(字符):
#include <stdio.h>
#include <string.h>
#define M_RW 100
#define M_CH 100
void ArrIn (char a[][M_CH], int &n)
{
for (int i = 0; i < n; i++)
{
printf("a[%d] = ", i);
gets(a[i]);
}
}
void ArrOut (char a[][M_CH], int n)
{
for (int i = 0; i < n; i++)
{
printf("a[%d] = %s\n", i, a[i]);
}
}
void ArrDel (char a[][M_CH], int &n, int position)
{
for (int i = position; i < n - 1 ; i++)
{
strcpy(a[i+1], a[i]);
}
n--;
}
void main()
{
char a[M_RW][M_CH];
int n, k;
printf("Number of row: n = "); scanf("%d", &n);
fflush(stdin);
printf("\n---\n\n");
ArrIn(a, n);
printf("\n---\n\n");
ArrOut(a, n);
printf("\n---\n\n");
printf("Want to delete row: k = "); scanf("%d", &k);
fflush(stdin);
ArrDel(a, n, k);
printf("\n---\n\n");
ArrOut(a, n);
printf("\n---\n\n");
}
编译后,输入一些数据:
+ n = 5;
+ a[0] = "Careless whisper";
+ a[1] = "I feel so unsure";
+ a[2] = "As I take your hand";
+ a[3] = "And lead you to the dance floor";
+ a[4] = "...";
+ k = 2;
我希望看到这样的结果:
+ a[0] = Careless whisper
+ a[1] = I feel so unsure
+ a[2] = And lead you to the dance floor
+ a[3] = ...
但是,它返回:
+ a[0] = Careless whisper
+ a[1] = I feel so unsure
+ a[2] = I feel so unsure
+ a[3] = I feel so unsure
我不知道为什么 a[1]
循环很多次。
你能告诉我:我在使用 strcpy
时出了什么问题吗?
最佳答案
问题是您将 strcpy()
的参数倒过来了。语法是strcpy(destination, source)
,所以当你写
strcpy(a[i+1], a[i]);
您在第一次迭代时从 a[2]
复制到 a[3]
,然后从 a[3]
复制到 a[4]
下一次迭代,依此类推。所以这会将 a[2]
复制到数组中的每个剩余条目。
将其更改为:
strcpy(a[i], a[i+1]);
关于c++ - 使用 `strcpy` 删除二维数组中的一行(字符)时是否有任何错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41356294/