Q2:实现以下函数ArrPrintMatrix(char *(p)[7])
,将matrix[m][7] ={"SHAHBAZ","AYAZ"}
的内容打印到3x3矩阵中
样本输出
S H AH B AZ A Y
我的问题是:这是我得到的唯一代码问题是一个名称完成后有一个空格。。如何删除该空间。我的作业中有这个问题,必须在周日(11-11-18(提交。。我的代码是:
#include<stdio.h>
int main()
{
void ArrPrintMatrix(char *p);//function declaration
char matrix[2][8] ={"SHAHBAZ","AYAZ"};//2d array initiliation
ArrPrintMatrix(&matrix[0][0]);//calling function with base address
}
void ArrPrintMatrix(char *p)
{
int i;
for(i=0;i<16;i++)
{
if(i>=9)//since 3 by 3 matrix is required
break;
if(i==3||i==6||i==9)//changing line since 3 by 3 matrix is needed
printf("n");
printf("%c ",*(p+i));//prininting chracters
}
}
您应该使用char (*p)[8]
而不是char* p
以下code
可以写入:
#include<stdio.h>
int main()
{
void ArrPrintMatrix(char (*p)[8]);//function declaration
char matrix[2][8] ={"SHAHBAZ","AYAZ"};//2d array initiliation
ArrPrintMatrix(matrix);//calling function with base address
}
void ArrPrintMatrix(char (*p)[8])
{
// i will point to one of the strings in the set of strings
// j will point into the string we are inspecting
// k will count how many characters we have printed
int i = 0, j = 0, k = 0;
// we only need to print the first 9 printable characters we find
while (k != 9)
{
// if we have reached the end of an input string (the null-terminator),
// then move on to the next element in the array, and reset
// the string pointer to the beginning of the new string
if (p[i][j] == ' ') {
++i;
j = 0;
}
// print the character we are now pointing at,
// and increment the string pointer
printf("%c ", p[i][j++]);
// keep count of how many characters we have printed
++k;
// if k is divisible by 3, start a new row
if(k%3 == 0)
printf("n");
}
}
作为我的另一个答案的后续,如果你确实使用我的逻辑跳过终止字符串的' '
,你将需要使用一个不同的变量来跟踪你实际打印了多少个字符,只需让i
跟踪你在输入字符串中的位置。像这样:
#include<stdio.h>
int main()
{
void ArrPrintMatrix(char *p);//function declaration
char matrix[2][8] ={"SHAHBAZ","AYAZ"};//2d array initiliation
ArrPrintMatrix(&matrix[0][0]);//calling function with base address
}
void ArrPrintMatrix(char *p)
{
int i, j;
for(i=0, j=0;i<16;i++)
{
if(j>=9)//since 3 by 3 matrix is required
break;
if(j==3||j==6||j==9)//changing line since 3 by 3 matrix is needed
printf("n");
if (*(p+i)==0) continue; //don't try to print the trailing ' '
printf("%c ",*(p+i));//prininting chracters
j++; //increment counter of characters actually printed
}
}
输出:
S H A
H B A
Z A Y
请注意j
变量的使用,以及在实际打印字符后如何仅使用j++
递增。
您缺少的是在SHAHBAZ
的末尾有一个尾随的' '
,您也在"打印"它,但由于' '
没有字符表示,您看到的是一个看起来像"额外"的空间。
这是我能想到的解决这个确切问题的最小变化;添加:
if (*(p+i)==0) continue; //don't try to print the trailing ' '
就在您现有的线路之上:
printf("%c ",*(p+i));//prininting chracters
输出:
S H A
H B A
Z A
还有其他事情我会做得和你现在做的不同,但这可以使用你的编码风格来解决你的确切问题。