【发布时间】:2018-08-21 09:50:56
【问题描述】:
/*implementation of strrev i.e. string reverse function*/
#include<stdio.h>
#include<string.h>
/*length of the string i.e. cells in the string*/
static const unsigned int MAX_LENGTH = 100;
//static const int MAX_LENGTH = -100;
/*reverses the string*/
void reverseString(char[]);
/*swaps the elements in the cells of a string*/
void swap(char[], int, int);
/*runs the program*/
int main()
{
char string[MAX_LENGTH];
//char string[0]; //no error!
//char string[-1]; //error!
gets(string);
reverseString(string);
printf("\n%s", string);
return 0;
}
void reverseString(char string[])
{
int i;
for(i = 0; i < (strlen(string) / 2); i++)
{
swap(string, i, (strlen(string) - 1 - i));
}
}
void swap(char string[], int i, int j)
{
int temp = string[i];
string[i] = string[j];
string[j] = temp;
}
看主函数。如果替换第一行“char string[MAX_LENGTH];”使用“char string[-1];”,编译器会显示错误。 (因为负长度的字符串没有意义)。但是,如果将此代码的第 7 行(我声明 const MAX_LENGTH)替换为第 8 行中用 cmets 编写的代码(其中 MAX_LENGTH 分配了 -ve 值),则不会出现编译错误。为什么?
另外,为什么声明零长度字符串没有错误。零长度字符串如何对编译器有意义但对负长度字符串没有意义?
【问题讨论】:
-
即使你没有得到编译错误,它仍然是未定义的行为。
-
gets已弃用。 -
@Inrin 你是对的。我从旧书上学到的。
-
您应该查看 C99 和/或 C11 标准。例如
for (int i=0...就更好了恕我直言。