Reputation: 51
I have this code trying out pointer with integers and there is a warning of initialization makes pointer from integer without a cast while compiling it. Also, it seems that after compilation the .exe file will not run properly. Please help!
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char* argv[]) {
int num1=10, *num2=1;
printf("num1=%d \t num2=%d \n", num1, *num2);
*num2 = num1;
printf("num1=%d \t num2=%d \n", num1, *num2);
return 0;
}
Upvotes: 1
Views: 3411
Reputation: 169
num2 is a pointer. So it is supposed to store an address. You can never store any INTEGER VALUE, like 1 you did, in it. A pointer is supposed to store an address. It can store ADDRESS of a variable. So I initialized your num2 with address of num1 integer variable and now your code works. If you are trying to initialize your num2 to get rid of garbage value, you can store NULL in num2. But make sure you do not dereference a null pointer (like using the statement printf(*num2) )because dereferencing a NULL pointer is a serious run time error,segmentation fault.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
int num1=10, num2=&num1; //this is what i have changed in your code
printf("num1=%d \t num2=%d \n", num1, *num2);
*num2 = num1;
printf("num1=%d \t num2=%d \n", num1, *num2);
return 0;
}
Upvotes: 1
Reputation: 29126
This:
int num1=10, *num2=1;
is equivalent to:
int num1 = 10;
int *num2 = 1;
The second variable is a pointer to int and when you assign a value to it or initialise it, you assign an address. You don't create a pointer to an integer whose value is 1.
That's what the warning means: You are converting an integer into a pointer, which is usually an error.
If you want a pointer to an int, you must create both:
int num2 = 1;
int *pnum2 = &num2; // pointer to num2, *num2 == 1
Upvotes: 3
Reputation: 75062
You converted an integer 1
to a pointer in implementation-defined manner, and the converted pointer has too little chance to be a valid pointer. As a result, dereferencing the pointer and read or write some value to it creates a big chance to cause Segmentation Fault.
Create an object to have the pointer point to, and have the pointer point to the object. Only after that, use the pointer to read or write values to where it points.
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char* argv[]) {
int obj = 0; /* do initialize before using the value */
int num1=10, *num2=&obj;
printf("num1=%d \t num2=%d \n", num1, *num2);
*num2 = num1;
printf("num1=%d \t num2=%d \n", num1, *num2);
return 0;
}
Upvotes: 5