Is there any error when deleting a row (of character) in 2D array, with `strcpy`?

101 views Asked by At

I am a newbie to programming. I write this simple code to delete a row (of character) in 2D array:

#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");

}

After I compile it, I input some data:

+ 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;

I would like to see result as this:

+ a[0] = Careless whisper
+ a[1] = I feel so unsure
+ a[2] = And lead you to the dance floor
+ a[3] = ...

But, it returns:

+ a[0] = Careless whisper
+ a[1] = I feel so unsure
+ a[2] = I feel so unsure
+ a[3] = I feel so unsure

I do not know why a[1] loop many times.


Could you show me: What I wrong when using strcpy?

1

There are 1 answers

0
Barmar On

The problem is that you have the arguments to strcpy() backwards. The syntax is strcpy(destination, source), so when you write

strcpy(a[i+1], a[i]);

you're copying from a[2] to a[3] on the first iteration, then a[3] to a[4] the next iteration, and so on. So this copies a[2] to every remaining entry in the array.

Change it to:

strcpy(a[i], a[i+1]);