Allocate memory for an array inside a struct

Discussion in 'C' started by MarounMaroun, Aug 28, 2010.

  1. MarounMaroun

    MarounMaroun New Member

    Joined:
    Aug 28, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hello All,
    I'm new here, and glad to be part of this wonderful and helpful site.

    I'm trying to allocate a new array (lets say of size 10) inside a struct.
    I want to do it this way:


    Code:
    typedef struct Circle {
        int *x;
        int y;
        int r;
    } Circle;
    
    typedef struct Circle* CircleP;
    typedef struct Circle Circle;
    
    //initialize array of size 10.
    CircleP allocateMem() {
        CircleP p=(CircleP) malloc(sizeof(Circle));
        p->x=(int*)malloc(sizeof(int) * 10);
        return p;
    }
    
    int main() {
        Circle circle;
        CircleP circleP=&circle;
        circleP=allocateMem();
        int i;
        for(i=0;ix[i]=i;
        int j;
        for(j=0;jx[i]);
        return 0;
    }
    The program do compile, but when I print the array I get 0 as its values.
    What I'm doing wrong?

    Thanks
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice