-1

I want to convert the type of the pointer 'p'. Begining ,the type of the pointer p is void .After allocating four bytes of memory for it, I cast pointer type into 'int',However ,this doesn't work . maybe the sentence p=(int *)p doesn't work.
Please tell me why and solve the problem.thanks.
The coding:

#include<stdio.h>
#include <stdlib.h>

 int main(void)
{
   void *p;
   p=malloc(sizeof(int));
   if(p == NULL)
    {
        perror("fail to malloc");
        exit(1);
    }
    p=(int *)p;
        *p=100;
    printf("the value is : %d\n",*p);

    return 0;
 } 
Jasonw
  • 5,054
  • 7
  • 43
  • 48
Jordan
  • 3
  • 3

4 Answers4

3

You'll have an easier time directly casting the void pointer returned by malloc to an int*

#include<stdio.h>
#include <stdlib.h>

int main(void)
{
   int *p;
   p = malloc(sizeof(int));
   if(p == NULL)
    {
        perror("fail to malloc");
        exit(1);
    }

    *p=100;
    printf("the value is : %d\n",*p);

    return 0;
 } 
GWW
  • 43,129
  • 11
  • 115
  • 108
  • 1
    Don't even need to go that far. Just make `p` an `int*` and not a `void*`. – Marlon Apr 25 '12 at 01:41
  • I know we're dealing with a corner case here, but I wouldn't recommend posting code that casts the return value from `malloc(3)` -- that cast can actually hide helpful warning messages from the compiler. – sarnold Apr 25 '12 at 01:47
  • [Don't cast the return value from malloc](http://stackoverflow.com/a/605858/241631) – Praetorian Apr 25 '12 at 01:48
  • could you tell me that the sentence 'p=(int *)p' could works ? – Jordan Apr 25 '12 at 01:48
  • Sorry I fixed that. It's a terrible habit I really need to break. – GWW Apr 25 '12 at 02:05
  • I'm sorry posting this code.I just begin to study Linux C ,so sometimes there are a lot of questions trouble me.I just want to know it. The last ,Thank you for your help – Jordan Apr 25 '12 at 02:16
  • you've better to use cast `p = (int*) malloc...`. – mattn Apr 25 '12 at 02:41
  • @mattn No, _don't_ cast the result of malloc ever in C. – Lundin Apr 25 '12 at 06:54
2

You can't change a variable's type after you have declared it. For what you are asking, you need to declare a separate int* variable and assign your p variable to it with the type-cast:

int *i = (int *)p; 
*i = 100; 
printf("the value is : %d\n", *i); 

Or, simply declare p as a int* to begin with and then type-cast the pointer returned by malloc(), like @GWW showed.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

You cant change a variables type, you can do a type cast but that is only temporary. what you want would be something like *(int*)p = 100; printf("the value is : %d\n", *(int*)p);

Musa
  • 96,336
  • 17
  • 118
  • 137
1

You can't. But you can create a new pointer to int and point to that position, like:

void *p;
p= malloc...
int *pi;
pi= p;
*pi= 25;
Gustavo Vargas
  • 2,497
  • 2
  • 24
  • 32