Pointer initialization doubt

Posted by Jestin Joy on Programmers See other posts from Programmers or by Jestin Joy
Published on 2011-01-06T03:47:59Z Indexed on 2011/01/06 3:58 UTC
Read the original article Hit count: 362

Filed under:
|

We could initialize a character pointer like this in C.

char *c="test";

Where c points to the first character(t).

But when I gave code like below. It gives segmentation fault.

#include<stdio.h>
#include<stdlib.h>
main()
{

 int *i;
 *i=0;
 printf("%d",*i);
}

But when I give

#include<stdio.h>
#include<stdlib.h>
main()
{
 int *i;
 i=(int *)malloc(2);
 *i=0;
 printf("%d",*i);
}

It works( gives output 0).

Also when I give malloc(0), It also works( gives output 0).

Please tell what is happening

© Programmers or respective owner

Pointer initialization doubt

Posted by Jestin Joy on Stack Overflow See other posts from Stack Overflow or by Jestin Joy
Published on 2011-01-06T04:29:46Z Indexed on 2011/01/06 4:54 UTC
Read the original article Hit count: 362

Filed under:
|
|
|

We could initialize a character pointer like this in C.

char *c="test";

Where c points to the first character(t).

But when I gave code like below. It gives segmentation fault.

#include<stdio.h>
#include<stdlib.h>
main()
{

    int *i=0;
    printf("%d",*i);
}

Also when I give

#include<stdio.h>
#include<stdlib.h>
main()
{
    int *i;
    i=(int *)malloc(2);
    printf("%d",*i);
}

It worked(gave output 0).

When I gave malloc(0), it worked(gave output 0).

Please tell what is happening

© Stack Overflow or respective owner

Related posts about c

    Related posts about pointers