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
?
The problem is that you have the arguments to
strcpy()
backwards. The syntax isstrcpy(destination, source)
, so when you writeyou're copying from
a[2]
toa[3]
on the first iteration, thena[3]
toa[4]
the next iteration, and so on. So this copiesa[2]
to every remaining entry in the array.Change it to: