【问题标题】:Initializing pointer to string: garbled text?初始化指向字符串的指针:乱码?
【发布时间】: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 的数组。它只有一个字符串终止符但没有内容的空间。尝试将任何其他字符串复制到它,除了空字符串,是未定义的行为。

标签: c string


【解决方案1】:

char ext[] = ""; 之后,extchar[1]。在get_extension 中,您尝试将整个扩展名写入其中,这显然不适合。写入超出数组的边界是未定义的行为,这意味着任何事情都可能发生。

【讨论】:

  • 谢谢。我被第一次正确打印字符串的事实误导了,由于某些错误的原因,我认为strcpy 会从空字符串开始自行调整数组的大小。
猜你喜欢
  • 2017-11-03
  • 1970-01-01
  • 2016-11-09
  • 2010-12-12
  • 2010-10-11
  • 1970-01-01
  • 2021-08-03
  • 2015-04-28
相关资源
最近更新 更多