我几天前才开始学习 C,我在使用指针时遇到了一些困难。我正在尝试将字符串转换为整数数组。下面的小片段似乎有效,但我收到警告:
在函数“charToInt32”中 警告:赋值使指针来自没有转换的整数[默认启用]| ||=== 构建完成:0 个错误,1 个警告(0 分钟,0 秒)===|
警告来自行
int32result[pos] = returnedInteger;
所以我想了解什么是最好的解决方案。我应该使用 strncpy(但我可以将 strncpy 用于整数吗?)或其他东西,还是我完全误解了指针?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int charToInt32(char * clearText, unsigned int * int32result[])
{
int i = 0, j = 0, pos = 0; /* Counters */
int dec[4] = {24, 16, 8, 0}; /* Byte positions in an array*/
unsigned int returnedInteger = 0; /* so we can change the order*/
for (i=0; clearText[i]; i+=4) {
returnedInteger = 0;
for (j=0; j <= 3 ; j++) {
returnedInteger |= (unsigned int) (clearText[i+j] << dec[j]) ;
}
int32result[pos] = returnedInteger;
pos++;
}
return pos;
}
int main()
{
int i = 0;
unsigned int * int32result[1024] = {0};
char * clearText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf(">>Clear: %s\n", clearText);
charToInt32(clearText, int32result); // Do the conversion to int32.
printf(">>Int32 converted: ");
for (i=0; int32result[i]; i++)
printf("%u ", (unsigned int) int32result[i]);
printf("\n");
return 0;
}
此外,在程序结束时我有以下行:
printf("%u ", (unsigned int) int32result[i])
将 int32result[i] 转换为 unsigned int 是避免再次警告将 %u 用于 unsigned int * 的唯一解决方案吗?
我确实检查了其他“Assignment makes integer from pointer without cast”主题/问题,但我无法从他们那里得到最终答案。
谢谢你的帮助。
最佳答案
unsigned int * int32result[1024]
声明了一个包含 1024 个 unsigned int
指针 的数组。我想你想要一个整数数组来代替
unsigned int int32result[1024]
您在 charToInt32
中遇到了类似的问题,其中 unsigned int * int32result[]
参数指定了一个 unsigned int
数组。您只有一个数组,因此可以传递 unsigned int * int32result
(即删除 []
)。
您的其余代码应该就可以正常工作了。调用方式
charToInt32(clearText, int32result);
相当于
charToInt32(clearText, &int32result[0]);
关于c - 赋值从整数生成指针,没有强制转换和其他问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16587672/