如何解决将空指针转换为整数指针
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
// fun() increments each element of the array a[] by 1.
void fun(void *ptr,int size)
{
// -The problem is we cannot dereference a float pointer to get integer values.
// We have to convert the float pointer to an integer pointer.
int *iptr = (int *)ptr;
for(int i = 0; i < size; i++)
{
iptr[i]++;
}
}
int main()
{
int a[5] = {10,2,3,14,51};
// Pass this array to the fun() function.
// a is a pointer to the address of the first element of the array.
printf("a = %p,*a = %d\n",a,*a); // a prints the address of the first element of the array a,and *a
prints the value of the first element of the array a.
fun((void *)a,5); // a is an integer pointer
// The problem is we need to convert a to a float pointer because that is the argument type in the
fun() function.
for(int i = 0; i < 5; i++)
{
printf("%d\n",a[i]);
}
return 0;
}
我的问题是我们不是在 fun 函数中将 void 指针“void *ptr”转换为整数指针吗?
如果答案是肯定的,那么我应该更改“我们不能取消引用浮点指针以获取整数值”的注释。它应该是“我们不能取消引用一个空指针来获取整数值”。请让我知道这个问题的正确答案是什么。谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。