debonair
debonair

Reputation: 2593

Changing the memory location of constant pointer

I have program

void alloc(char **p)
{
     *p=(char*)malloc(sizeof(char)*3);
        (*p)[0]='a';
    (*p)[1]='f';
    (*p)[2]='\0';

}
main()
{
    char p[]="hrrgr";
    alloc(&p);

    printf("%s",p);
}

It prints nothing. Please explain this. I know by passing char*p ; and alloc(&p) will do the trick. But the purpose of my question is to understand the output I am getting.

Upvotes: 0

Views: 66

Answers (4)

ajay
ajay

Reputation: 9680

p is an array of 6 characters. Therefore p is of type char[6]. &p is then of type pointer to char[6] type, i.e., char (*)[6]. When you pass an array to a function, it evaluates to a pointer to its first element. Thus when you are passing a char (*)[6] type value to your alloc function, you are assigning a char (*)[6] type to a char ** type. They are incompatible types and have different pointer arithmetic. You can't make char (*)[6] behave like a char ** type, even by typecasting which will only suppress compiler warning.

Upvotes: 2

Devavrata
Devavrata

Reputation: 1805

try this...

void alloc(char **p)
{
    *p=(char*)malloc(sizeof(char)*3);
    (*p)[0]='a';
    (*p)[1]='f';
    (*p)[2]='\0';
 }
 main()
{
   char *p;
   alloc(&p);
   printf("%s",p);
 }

When ever you declare an array then there will be continuous allocation of memory but here your are changing starting 3 elements memory which changes the whole location of array and printing garbage...

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726969

This is not allowed: p is an array of 6 characters, not a char pointer. You should not treat &p as a char** pointer.

If you want to fix this code, declare p like char*, not as an array:

char *p="hrrgr";
alloc(&p);

Running demo on ideone.

Upvotes: 2

haccks
haccks

Reputation: 106102

&p is of type char (*)[6] but your function alloc expects an argument of type char **. You are passing wrong type parameter.

Upvotes: 1

Related Questions