A Developer's Diary

Jan 20, 2011

Pointers in C - an eye opener

My friend once asked me a problem in C involving struct and pointers. I was confident that the solution I had proposed would work untill I finally gave it a try.
Among the common mistakes i could not avoid were not allocating memory before trying to use the pointers and trying to dereference a pointer as p->q->*num :)

#include <stdio.h>

struct B
{
    char *str;
    int  *num;
};

struct A
{
    struct B *q;
};

int main()
{
    char *tstr = "Hello World";

    /**
     * 1. The program should copy the value tstr in str and print it
     * 2. The program should assign value 100 to num and print it 
     */
    struct A *p;
}

Posting the complete program showing the memory allocation and pointer dereferencing
#include <stdio.h>

struct B
{
    char *str;
    int  *num;
};

struct A
{
    struct B *q;
};

void* mem_alloc(size_t size)
{
    void *ptr = (void *) malloc(size);
    if(NULL == ptr)
    {
        printf("ERROR: Insufficient Memory");
        exit(-1);
    }
    return ptr;
}

int main()
{
    char *tstr = "Hello World";

    struct A *p;

    //allocate memory
    p         = (struct A*) mem_alloc(sizeof (struct A));
    p->q      = (struct B*) mem_alloc(sizeof (struct B));
    p->q->str = (char *)    mem_alloc(strlen (tstr));
    p->q->num = (int *)     mem_alloc(sizeof (int));

    //assign values
    strcpy(p->q->str, tstr);
    *p->q->num = 100;

    //print values
    printf("%s\n", p->q->str);
    printf("%d\n", *p->q->num);
    return 0;
}

No comments :

Post a Comment