gpt4 book ai didi

c - 初始化指向字符串 : garbled text? 的指针

转载 作者:行者123 更新时间:2023-11-30 14:37:59 25 4
gpt4 key购买 nike

初始化指向 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[] = "";之后,ext是一个char[1]。在 get_extension 中,您尝试将整个扩展写入其中,这显然不适合。超出数组范围的写入是未定义行为,这意味着任何事情都可能发生。

关于c - 初始化指向字符串 : garbled text? 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com