/* code for showing: most common error in pointer is assigning a value()not address to pointer without mallocing it. Before this note the declaration like int *ptr; tells the compiler that it will store address of an integer and not a value directly*/
#include<stdio.h>
#include<stdlib.h>
main()
{
/*case when pointer need to malloced:when ptr is directly assigned with VALUE and not address*/
int *p;//p is pointer so should store address and not value.
// *p=10;///Ptr Error: assigning value(not address) to pointer mallocing
//printf("%d\n",*p);//as a result segfault
/*so allocate memory for ptr then assign valut to pointer*/
p=malloc(1*sizeof(int));
*p=10;
printf("%d\n",*p);
/*Error not freeing memory allocated dynamically cause mem leak*/
free(p);
/*case when pointer need not to malloced: when ptr is assigned with ADDRESS and not vakue*/
int *q;//this statement tells the compiler that q will store address of an integer.
int a=10;
q=&a;//no allocation required for q when address is assigned to pointer
printf("a=%d\n\n",*q);//some times work but not always without malloc
}
Also understand well declaration of variables and pointers very well to avoid errors/bug:
int i=20;//This declaration tells three things to compiler. reserve memory for a int size, name it i and store 20 there.
int *p;//tells the compiler that p will be used to store base address of an integer.
char *p;//tells the compiler that p will be used to store base address of a string.
char *ptr="Ram"; is valid as ptr is assigned with the base address of string ie char array since name of an array gives the base address and not value.
int *p=10;//will be an array as here pointer is assigned a value and not address like above statement.
Solution in this case will be to first allocate memory then assign value.
*so allocate memory for ptr then assign valut to pointer*/
p=malloc(1*sizeof(int));
*p=10;
printf("%d\n",*p);
No comments:
Post a Comment