马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
抛开字符数组的越界访问不谈,这两种写法为什么输出不一样呢?
终止条件在循环体内:#include <stdio.h>
#include <string.h>
int main()
{
char* str[5] = {"FishC", "Five", "Star", "Good","WoW"};
char* (*ptr)[5] = &str;
int max = strlen((*ptr)[1]);
for (int i = 0; i < 5; i++) {
max = strlen((*ptr)[i]) > max ? strlen((*ptr)[i]) : max;
}
for (int i = 0; i <= max - 1; i++) {
for (int j = 0;j < 5; j++) {
if((*ptr)[j][i] == '\0'){
break;
}
printf("%c ",(*ptr)[j][i]);
}
printf("\n");
}
return 0;
}
输出:F F S G W
i i t o o
s v a o w
h e r d
C
Process finished with exit code 0
终止条件放在for语句内:#include <stdio.h>
#include <string.h>
int main()
{
char* str[5] = {"FishC", "Five", "Star", "Good","WoW"};
char* (*ptr)[5] = &str;
int max = strlen((*ptr)[1]);
for (int i = 0; i < 5; i++) {
max = strlen((*ptr)[i]) > max ? strlen((*ptr)[i]) : max;
}
for (int i = 0; i <= max - 1; i++) {
for (int j = 0;(*ptr)[j][i] != '\0'; j++) {
printf("%c ",(*ptr)[j][i]);
}
printf("\n");
}
return 0;
}
输出:F F S G W
i i t o o ?
Process finished with exit code -1073741819 (0xC0000005)
本帖最后由 jhq999 于 2022-9-11 17:09 编辑 for (int j = 0;(*ptr)[j][i] != '\0'&&j<5; j++) {//&&j<5,没有 i=1,j=5,(*ptr)[5][2]已经越界而不遇到‘\0’,就是死循环
printf("%c ",(*ptr)[j][i]);
}
|