c++ - 使用 `strcpy` 删除二维数组中的一行(字符)时是否有任何错误?

标签 c++ arrays strcpy

我是编程新手。我写了这个简单的代码来删除二维数组中的一行(字符):

#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/

相关文章:

c - 数组中正值的总和在 c 程序中给出负结果

c - C语言中如何替换变量名

c++ - strcpy_s 复制超过字符串长度到目标缓冲区(用 0xFE 填充)

c++ - 在代码块中安装外部 'library?'

c++ - 当 dif==0 时该过程将停止,但当 dif==-0.000000 时它不会停止

javascript - 使用数组中的键获取值 - Angularjs

c - 在函数中访问内存 malloc 时出现段错误

c++ - 如何在 *.cpp 文件中实现静态类成员函数?

c++ - 如何将 QPen 与 QpainterPath 一起使用?

c++ - 数组循环无输出