2011-01-14 48 views
1

我有一个变量'jmp_code',声明为char *。当我运行以下命令不同的结果使用%c和循环与printf中的循环与%s以空值终止的字符串

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; 

} 

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

感谢

+0

我认为这与jmp_code的内容有关。 'α'不是ASCII字符。 – wong2 2011-01-14 14:38:54

+0

你的环境是什么?你能粘贴完整的代码吗? – 2011-01-14 14:45:08

+0

令人惊叹。 char_array在some_func()函数的堆栈上,您提供它并返回指针。据我所知,printf可以打印所有的东西。 尝试在%c%c%c之前打印%s,您可能会有第二次打印的奇怪行为... – 2011-01-14 15:29:31

回答

1

我觉得字符类型不能使用非ASCII字符代码。这意味着您的字符串包含UTF-8或类似符号,代码可能位于(0,over9000)范围内,而char代码可能位于(0,255)范围内。

2

这可能是有趣的,看看:

const char *pos = jmp_code; 
while (*pos) 
    printf("%d ", *pos++); 
+0

导致无限循环。我添加了以下内容 printf(“按编号分类,代码为'%d,%d,%d,%d,'\ n”,* pos,*(pos + 1),*(pos + 2 ),*(POS + 3)); 其中导致 数字的数字,代码是'-108,92,-61,119,' – Justin 2011-01-14 15:28:48

2

你返回到一个临时数组的引用。当some_func() retuns时,char_array消失,但您继续使用它的地址。您需要使用malloc()分配一个数组,然后在使用它之后使用free()

4

一些快速意见:

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

您不能分配在C使用=字符串弄​​乱的东西了 - 你要指定代码的您本地分配char_array代码指针,但你不复制内存的内容。另请注意,由于char_array在堆栈上(通常)被分配,因此当您从该函数返回时,您会发现它会消失。你可以用static关键字解决这个问题,但我认为这不是最好的解决方案。您应该使用的线沿线的东西(大警告这个例子中,没有大量的安全,你需要检查字符串的长度,但为了简洁的缘故):

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

(参见this(和this )为安全的字符串处理建议)。

并通过主要的some_func(jmp_code)进行调用。如果你不确定这是什么,请阅读pointers

第二个问题。

char * jmp_code = NULL; 

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

我在想什么?好了,我的系统上,我得到:

,代码为“0,0,0 ,,”和代码 是“”

但我认为这是机会,jmp_code指向您的some_func函数提供的堆栈中的零。我想在你的系统上数据已被覆盖。

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

2

您正在从无效指针打印。 char_array在some_func()函数的堆栈中。
该函数返回堆栈中的东西的指针,并且在函数返回后不会再出现!
第一个printf发现堆栈保持不变,第二个,也许,发现它充满...垃圾!