这个编程接受一个字符数组n压缩它们....(aaaabbbcc - > a4b3c2)....我的编程显示错误在我将2d数组的addr等同于1d阵列。这是我的代码:
/* size1 defined as 5 and size2 as 10.... (consts)*/
void compress(char data[SIZE1][SIZE2]);
int main()
{
char data[SIZE1][SIZE2];
printf("Enter a 5x10 matrix of characters:\n");
scanf("%c", &data);
compress(data[SIZE1][SIZE2]);
_getch();
return 0;
}
void compress(char data[SIZE1][SIZE2])
{
int hold[SIZE1*SIZE2];
int cnt = 0;
hold[SIZE1*SIZE2] = data[SIZE1][SIZE2];
for (int i = 0; i < (SIZE1*SIZE2); i++)
{
if (hold[i] == hold[i + 1])
{
cnt++;
continue;
}
else
{
printf("%c%d", hold[i], cnt);
}
}
}
这没用,所以我尝试使用指针:
void compress(char data[SIZE1][SIZE2])
{
int *hold[SIZE1*SIZE2];
int cnt = 0;
hold = data[SIZE1][SIZE2];
for (int i = 0; i < (SIZE1*SIZE2); i++)
{
if (*(hold+i) == *(hold+i+1))
{
cnt++;
}
else
{
printf("%c%d", *(hold+i), cnt);
}
}
}
我认为2d数组的加法器是线性存储的,因此它们可以直接= 1d的数据。但错误说“'=':左操作数必须是l值”。这对指针来说很新。任何帮助或更正......请问?
答案 0 :(得分:2)
#include <stdio.h>
#define SIZE1 3
#define SIZE2 3
void compress(char data[SIZE1][SIZE2]);
int main(){
char data[SIZE1][SIZE2];
printf("Enter a %dx%d matrix of characters:\n", SIZE1, SIZE2);
for(int i=0;i<SIZE1;++i)
for(int j=0;j<SIZE2;++j)
scanf("%c", &data[i][j]);//aaaabbbcc
compress(data);
(void)getchar();
return 0;
}
void compress(char data[SIZE1][SIZE2]){
char *hold = &data[0][0];
int cnt = 1, size = SIZE1*SIZE2;
for (int i = 0; i < size; i++){
if (i < size -1 && hold[i] == hold[i + 1]){
cnt++;
//continue;
} else {
printf("%c%d", hold[i], cnt);//a4b3c2
cnt = 1;
}
}
}