Question: Can a Pointer in C Automatically Allocate Memory When it is Declared
Answer: As we know Pointer is like any ordinary variable in that when it is declared, compiler allocates it a location in memory. Every location has an address and contents. The contents of a pointer is, however, address; address of some ordinary variable, other pointer or some function etc.. For example:
/* * mem_alloc_to_ptr.c -- Program shows memory is allocated to ptr when * declared */ #include <stdio.h> int main(void) { int *ip, *ip1; /* pointer to integer declared */ int boys = 100; /* boys an int is initialized to 100 */ ip = &boys; /* ip holds the address of boys */ printf("\nAddress of pointer to integer \"ip\" in exp. \"ip = &boys\" " "is %p\nand its contents, an address is %p\nand value it points" " to is %d\n", &ip, ip, *ip); printf("\npointer to integer \"ip1\" is declared but not initialized..." "\n"); printf("Its Address in memory %p\nits contents, garbage address %p\n", &ip1, ip1); /* contents of ip1 is garbage address */ printf("\n"); return 0; }
Above program when I run on my Linux system produces output as:
Address of pointer to integer "ip" in exp. "ip = &boys" is 0x7fffb7807088 and its contents, an address is 0x7fffb780707c and value it points to is 100 pointer to integer "ip1" is declared but not initialized... Its Address in memory 0x7fffb7807080 its contents, garbage address 0x7fffb7807170
Notice that even if a pointer is declared but not initialized, it holds Garbage address. Be sure not to dereference an uninitialized pointer!
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
advertisement
advertisement
If you wish to look at all C Tutorials, go to C Tutorials.
Related Posts:
- Apply for Computer Science Internship
- Practice BCA MCQs
- Apply for C Internship
- Check Computer Science Books
- Practice Computer Science MCQs