我想知道为什么这个程序在没有分段错误的情况下工作:
#include <stdio.h>
char *month_name(int);
main()
{
char *month[15];
for(int i = 1, j = 0; month_name(i) != "No month"; i++, j++)
{
month[j] = month_name(i);
while(*month[j])
{
printf("%c", *month[j]++);
if(!*month[j])
{
printf("\n");
}
}
}
}
char *month_name(int num)
{
static char *name[] = {
"No month", "January", "February",
"Mart", "April", "May", "June",
"July", "August", "September", "October",
"November", "December"
};
return (num < 1 || num > 12) ? name[0] : name[num];
}
而这个有分段错误并在屏幕上显示奇怪的字符:
#include <stdio.h>
char *month_name(int);
main()
{
char *month[15];
int k = 0;
for(int i = 1, j = 0; month_name(i) != "No month"; i++, j++)
{
month[j] = month_name(i);
}
!!!!!
while(*month[k])
{
printf("%c", *month[k]++);
if(!*month[k])
{
printf("\n");
k++;
}
}
!!!!!
}
char *month_name(int num)
{
static char *name[] = {
"No month", "January", "February",
"Mart", "April", "May", "June",
"July", "August", "September", "October",
"November", "December"
};
return (num < 1 || num > 12) ? name[0] : name[num];
}
像这样
一般不能写。如果它正确地为您工作,那么仅仅是因为优化,它结合了相同的只读行。一旦您将带有密钥的代码编译到 VC++
/GF-
中,一切都会立即停止工作......在第二种情况下,您只需遍历指针数组(因为
k++
)并在 12 月跳出到下一个指针 - 它包含某种指向其他垃圾的垃圾,这些垃圾正试图退出或崩溃。所以如果你写
那么一切都会奏效:)