【发布时间】:2015-09-22 07:06:35
【问题描述】:
我正在尝试为十六进制到二进制转换创建一个 c 函数,但出现奇怪的错误,我对 C 很陌生。尝试传递字符串但没有运气得到一堆错误。
#include<stdio.h>
#include<string.h>
char *hexc(char hex[10]);
int main(){
char hex[10];
//char bin[1000];
scanf("%c",&hex[10]);
printf("binary value: %s",hexc(hex[10]));}
char *hexc(char hex[10])
{
const char binary[16][5] = {"0000", "0001", "0010", "0011", "0100", "0101","0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110","1111"};
const char digits[] = "0123456789abcdef";
const char input[100]; // input value
memcpy (input,hex,100);
char res[1024];
res[0] = '\0';
int p = 0;
int value =0;
while(input[p])
{
const char *v = strchr(digits, tolower(input[p]));
if(v[0]>96){
value=v[0]-87;
}
else{
value=v[0]-48;
}
if (v){
strcat(res, binary[value]);
}
p++;
}
printf("binary: %s", res);
return res;}
错误列表,尝试了多次谷歌搜索但没有运气。
test2.c: In function ‘main’:
test2.c:9:1: warning: passing argument 1 of ‘hexc’ makes pointer from integer without a cast [enabled by default]
printf("binary value: %s",hexc(hex[10]));}
^
test2.c:3:7: note: expected ‘char *’ but argument is of type ‘char’
char *hexc(char hex[10]);
^
test2.c: In function ‘hexc’:
test2.c:16:1: warning: passing argument 1 of ‘memcpy’ discards ‘const’ qualifier from pointer target type [enabled by default]
memcpy (input,hex,100);
^
In file included from test2.c:2:0:
/usr/include/string.h:46:14: note: expected ‘void * __restrict__’ but argument is of type ‘const char *’
extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
^
test2.c:36:28: warning: function returns address of local variable [-Wreturn-local-addr]
printf("binary: %s", res); return res;}
【问题讨论】:
-
阅读几本不错的C编程书籍
-
这里:
scanf("%c",&hex[10]);,越界访问。这是未定义的行为,所有赌注都已取消。你必须解决这个问题。 -
编译器的哪个错误你不明白?
-
hexc(hex[10]))也是越界访问。 -
专业提示:问题是一系列以问号结尾的单词,经过精心设计,我们知道您在寻找什么信息。没有您的问题,所以我们不知道您在寻找什么信息。也许您的意思是就您可能不理解的警告提出问题?与其强迫我们把你当成你不懂任何东西(你真的希望我们那样对待你吗?),为什么不告诉我们这些警告中的哪些词引起了你的困惑呢?这将为我们节省大量时间,并可能为您节省大量情绪困扰。
标签: c arrays string function pointers