发布时间:2019-07-29 22:03:09
代码:
#include <stdio.h>
#include <stdlib.h>
void longestCommonPrefix(char **strs){
for(int i = 0;i < 3; i++)
{
for(int j = 0; j < 7;j++)
printf("%c",strs[i][j]);
printf("\n");
}
}
int main()
{
char s[3][7] = {"flower","flow11","flight"};
longestCommonPrefix(s);
return 0;
}
在主函数中的二维数组 s[3][7] 也用指针表达,输出的时就不会出现乱码,而能正确运行了:
程序如下:
#include <stdio.h>#include <stdlib.h>void longestCommonPrefix(char **strs) {int i,j; for(i = 0;i < 3; i++) { for(j = 0; j < 7;j++) printf("%c",strs[i][j]); printf("\n"); } }int main(){ char **s[] = {"flower","flow11","flight"}; longestCommonPrefix(s); getch(); return 0;}
在C语言中,一维数组等价于一维指针,而二维数组不能等价二维指针的,因为它不能确定第二下标的值
你的 char s[3][7] 对应的正确的指针参数为 char (*)[7],也就是二维数组作为指针参数,必须指定第二下标的值 ,以下完全OK的
void longestCommonPrefix(char (*strs)[7]){ for(int i = 0;i < 3; i++)
{ for(int j = 0; j < 7;j++)
printf("%c",strs[i][j]);
printf("\n");
}}
或直接将它变成一维的指针
void longestCommonPrefix(char *strs){
for(int i = 0;i < 3; i++)
{
for(int j = 0; j < 7;j++)
printf("%c",strs[7*i+j]); //这里要换算
printf("\n");
}
}