警告:赋值从指针生成整数而不进行强制转换
#include <stdio.h>
#include <string.h>
#include <math.h>
#define NUM 8
int main() {
int i, len, sum, offset, remain;
char bin[32];
char hexlist[6][1] = {"A", "B", "C", "D", "E", "F"};
char hex[NUM] = "00000000";
int hexlen = NUM;
while (1) {
scanf("%s", bin);
if (strcmp(bin, "0") == 0) {
break;
}
len = strlen(bin);
offset = 0;
while (offset < len) {
sum = 0;
if (len - offset >= 4) {
for (i = 0; i < 4; i++) {
sum += (bin[len-1-i-offset] - '0') * pow(2, i);
}
}
else {
remain = len - offset;
for (i = 0; i < remain; i++) {
sum += (bin[len-1-i-offset] - '0') * pow(2, i);
}
}
if (sum > 10)
// I got "warning: assignment makes integer from pointer without a cast"
hex[--hexlen] = hexlist[sum%10];
else
hex[--hexlen] = (char)(((int)'0')+sum);
offset += 4;
}
printf("%s\n", hex);
}
return 0;
}
我尝试了 hex[--hexlen] = (char)hexlist[sum%10];
,但收到“警告:从指针转换为不同大小的整数”
#include <stdio.h>
#include <string.h>
#include <math.h>
#define NUM 8
int main() {
int i, len, sum, offset, remain;
char bin[32];
char hexlist[6][1] = {"A", "B", "C", "D", "E", "F"};
char hex[NUM] = "00000000";
int hexlen = NUM;
while (1) {
scanf("%s", bin);
if (strcmp(bin, "0") == 0) {
break;
}
len = strlen(bin);
offset = 0;
while (offset < len) {
sum = 0;
if (len - offset >= 4) {
for (i = 0; i < 4; i++) {
sum += (bin[len-1-i-offset] - '0') * pow(2, i);
}
}
else {
remain = len - offset;
for (i = 0; i < remain; i++) {
sum += (bin[len-1-i-offset] - '0') * pow(2, i);
}
}
if (sum > 10)
// I got "warning: assignment makes integer from pointer without a cast"
hex[--hexlen] = hexlist[sum%10];
else
hex[--hexlen] = (char)(((int)'0')+sum);
offset += 4;
}
printf("%s\n", hex);
}
return 0;
}
I tried hex[--hexlen] = (char)hexlist[sum%10];
, but I got "warning: cast from pointer to integer of different size"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想要的是这样的:
在 C 中,双引号之间的字符常量表示一个字符串,并以空字符
\0
结尾。单引号之间的字符常量表示单个字符。What you want is this:
In C a character constant between double quotes indicates a string of characters, and is ended with a null character
\0
. A character constant between single quotes indicates a single character.hexlist
是一个数组的数组,hexlist
的每个元素都是一个数组...并且通常对此类数组的引用会衰减为指针。这就是代码中发生的情况:hexlist[sum % 10]
是char[1]
类型的对象,并衰减为指针。然后,您尝试将该指针分配给
char
类型的hex
元素。这些类型不兼容,并且在默认升级之后,编译器会抱怨。hexlist
is an array of arrayseach element of
hexlist
is an array ... and usually references to such arrays decay to pointers. That's what is hapenning in your code:hexlist[sum % 10]
is an object of typechar[1]
and decays to a pointer.You then try to assign that pointer to an element of
hex
, of typechar
. The types are incompatible and after the default promotions, the compiler complains.