【发布时间】:2019-07-06 20:14:45
【问题描述】:
在初始化指向 char 数组的指针后,我得到了乱码文本和错误的返回值。我完全不明白。我使用 Linux gcc 作为编译器。
也尝试使用此在线编译器,结果相同: https://www.onlinegdb.com/online_c_compiler
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
// Prototypes -------------------------------------------------------------{{{1
void get_extension(const char *file_name, char *extension);
bool test_extension(const char *file_name, const char *extension);
// Main function ----------------------------------------------------------{{{1
int main()
{
printf("%d\n", test_extension("name.txt", "txt"));
return 0;
}
// Functions definitions --------------------------------------------------{{{1
void get_extension(const char *file_name, char *extension)
{
int i;
strcpy(extension, "");
for (i=0; i < strlen(file_name) - 1; ++i)
if ( file_name[i] == '.' ) break;
if ( i == strlen(file_name) - 1 ) return;
strcpy(extension, &file_name[i+1]);
}
bool test_extension(const char *file_name, const char *extension)
{
char ext[] = "";
get_extension(file_name, ext);
printf("%s %s\n", ext, extension); // values before pointer init
char *p = ext;
printf("%s %s\n", ext, extension); // why did the string change??
while ( *extension )
if ( toupper(*p++) != toupper(*extension++) ) return 0;
return 1;
}
我希望返回值为 1,并且在第二次 printf() 调用中不会出现乱码。
【问题讨论】:
-
char ext[] = "";定义了一个大小为1的数组。它只有一个字符串终止符但没有内容的空间。尝试将任何其他字符串复制到它,除了空字符串,是未定义的行为。