c - 在带有空终止字符串的 printf 中使用 %c 和循环与 %s 的不同结果

标签 c string printf

我有一个声明为 char * 的变量“jmp_code”。当我运行以下命令时

printf("char by char, the code is '%c%c%c%c'\n", *jmp_code, *(jmp_code+1), *(jmp_code+2),*(jmp_code+3));
printf("printing the string, the code is '%s'\n", jmp_code);

我得到以下结果

char by char, the code is '0,0,0, ,'
printing the string, the code is 'ö\├w≡F┴w'

我正在使用代码块。这是我正在玩的示例代码。

#include <stdio.h>
#include <string.h>

char * some_func(char * code);

char * some_func(char * code) {

    char char_array[4];

    strcpy(char_array, "000");

    code = char_array;

    return code;

}
int main ( void ) {

    char * jmp_code = NULL;

    jmp_code = some_func(jmp_code);

    printf("char by char, the code is '%c,%c,%c,%c,'\n", *jmp_code, *(jmp_code+1), *(jmp_code+2),*(jmp_code+3));
    printf("printing the string, the code is '%s'\n", jmp_code);

    return 0;

}

我对此很困惑。任何帮助将不胜感激。

谢谢

最佳答案

一些快速观察:

char * some_func(char * code) {
    char char_array[4];
    strcpy(char_array, "000");
    code = char_array;
    return code;
}

您不能在 C 中使用 = 分配字符串。这会把事情搞砸 - 您将本地分配的 char_array 的指针分配给 code,但是您'不是在复制内存的内容。另请注意,由于 char_array 是在堆栈上分配的(通常),您会发现当您从该函数返回时它会消失。您可以使用 static 关键字来解决这个问题,但我认为这不是这里最好的解决方案。你应该使用类似的东西(重要警告这个例子不是非常安全,你确实需要检查字符串长度,但为了简洁起见):

void some_func(char * code) {
    strcpy(code, "000");
    return;
}

(有关安全字符串处理建议,请参阅 this(和 this))。

然后在 main 中通过 some_func(jmp_code) 调用它。如果您不确定这是做什么的,请继续阅读 pointers .

第二个问题。

char * jmp_code = NULL;

目前,您已经为指向 char 类型的指针声明了足够的空间。如果你想使用我上面的建议,你需要使用 malloc()free() 或者声明 char jmp_code[4] 代替,以便分配空间。

我认为发生了什么?那么,在我的系统上,我得到:

and the code is '0,0,0,,' and the code is ''

但我认为 jmp_code 有可能指向您的 some_func 函数提供的堆栈上的零。我认为在您的系统上数据已被覆盖。

相反,您正在阅读您的终端解释为所述字符的信息。阅读字符编码。我特别建议从 The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) 开始

关于c - 在带有空终止字符串的 printf 中使用 %c 和循环与 %s 的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4692060/

相关文章:

c - ISO C99 printf ("%Nd"的前导零默认行为)?

c - scanf 跳过一行

在代码中计算

c - Linux block 系统调用

c# - 找到搜索数据结构字符串比较的最佳方法

java - 从特殊字符串包围的字符串中提取两个子字符串(Java)

c - 为什么 printf 对 double 输出随机值,对 int 输出 0.000000 随机值?

c - ftell 返回不正确的值

c - printf 之后打印额外的数字

C++ - 使用临时变量索引数组