gpt4 book ai didi

c - 为什么指针在传递给函数时在某些情况下表现不同?

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:19 24 4
gpt4 key购买 nike

我有这个代码示例,我无法弄清楚为什么 sscanf 在示例函数中按预期工作,但在主函数中却没有。

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

void example(char *seq){
char wert;
while(*seq){
sscanf(seq,"%2x",&wert);
fprintf(stdout,"%c",wert);
seq+=2;
}
}

int main() {
char temp;
char sentence []="1B2873313648";
char *seq=sentence;
example(seq);
printf("\n");
while(*seq){
sscanf(seq,"%2x",&temp);
fprintf(stdout,"%c",temp);
seq+=2;
}
}

最佳答案

sscanf 格式说明符 %x 需要指向 unsigned int 的指针,而不是指向 char 的指针,所以所有的赌注都因未定义的行为而关闭。请注意编译器警告。在我的 MSVC 上,此代码导致崩溃。

此更正后的代码有效。

#include <stdio.h>          // missing
#include <stdlib.h>
#include <string.h>

void example(char *seq){
unsigned wert;
while(*seq){
sscanf(seq,"%2x",&wert);
fprintf(stdout,"%02X ",wert);
seq+=2;
//fflush(stdin);
}
}

int main() {
unsigned temp;
char sentence []="1B2873313648";
char *seq=sentence;
example(seq);
printf("\n");
while(*seq){
sscanf(seq,"%2x",&temp);
fprintf(stdout,"%02X ",temp);
seq+=2;
//fflush(stdin);
}
}

程序输出:

1B 28 73 31 36 481B 28 73 31 36 48

关于c - 为什么指针在传递给函数时在某些情况下表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55959028/

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