【发布时间】:2013-04-12 11:40:34
【问题描述】:
我刚刚浏览了一些面试问题,发现这段代码使用指针反转字符串。但我看到他们在这里定义了限制字符串长度的 char string[100] 。我不太擅长 C。如何修改它以使其成为任意长度的字符串?
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer+c) != '\0' )
c++;
return c;
}
【问题讨论】:
-
您可以将
length(string_length的结果)用于end。 -
这不是一个“反向字符串”问题,因为这部分很好,它正在读取字符串问题。
-
不要使用
gets();它不在 C2011 中,无法安全使用。使用fgets()或POSIXgetline()。