错误:无效指针的使用无效

时间:2014-10-14 05:20:08

标签: c

阅读无效指针: -

  1. 当我们将整数地址分配给void指针时,指针将变为Integer Pointer。
  2. 当我们将字符数据类型的地址分配给void指针时,它将变为Character Pointer。
  3. 代码:

      void main()
      {
      float f = 111.35;
      void * fp;
      fp = &f;
      printf("%.2f\n",*fp);
      }
    

    它显示以下错误:void指针的使用无效 如果我将指针的类型更改为float * fp,则没有错误。

3 个答案:

答案 0 :(得分:2)

void指针的类型是"指向void&#34的指针;没有别的。由于void没有类型,因此在解除引用时必须将其显式转换为正确的类型,例如

*(float *) fp;

答案 1 :(得分:0)

您的变量类型必须在printf之前或printf中指定,因此在将其转换为正确类型的c之前,您无法访问void *变量。

答案 2 :(得分:0)

The prime benefit of using void pointer is its reusability.
You can use fp to point to a char* or int* or float* in successive statements.
When you state vp =&f, it implies that vp can act as a float pointer.
It does not become a float pointer.
So when you dereference it ( as in printf), you need to typecast it.

int main()
{
int iVal = 9;
float fVal = 9.0;
void *ptr;

ptr = &iVal; 
printf("iVal = %d\n",*((int*)ptr)); //De-referencing

//Resuability
ptr = &fVal;  
printf("fVal = %f\n",*((float*)ptr)); //De-referencing

return(0);
}