微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将空指针转换为整数指针

如何解决将空指针转换为整数指针

#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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?