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:

#include <stdlib.h>
#include <stdio.h>

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;i<10;i++)
        circleP->x[i]=i;
    int j;
    for(j=0;j<10;j++)
        printf("%d\n", circleP->x[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

Edited by MarounMaroun: n/a

2
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by MarounMaroun
0

wow... I can't believe I did that..
Is everything beside that ok? That's how I should allocate memory to an array inside a struct?

1

Besides checking a return value, allocation is OK. Lines 22-24 look strange though. A simple

CircleP circleP = allocateMem();

is enough.

Edited by nezachem: n/a

0

Thanks nezachem.. I'm new in programming and specially in c.
This Forum is really helpful, many topics helped me a lot for now.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.