I am having a problem in a program I am writing. This small program is a short version just to show the problem.
For this example, I am defining a structure called point which has an X and Y. I want the function to calculate the number of points, In this example I am assuming always 5, but this is not constant in my real program.
#include <stdio.h>
typedef struct point {
int x;
int y;
}point;
// suppose this is dynamic. it return a value according to some parameter;
int howManyPoints() {
// for this demo assume 5.
return 5;
}
int createAnArrayOfPoints(point** outArray,int* totalPoints) {
// how many points?
int neededPoints = howManyPoints();
// create an array of pointers
*outArray =malloc(neededPoints * sizeof(point*));
// malloc memory of a point size for each pointer
for (int i=0;i<neededPoints;i++) outArray[i] = malloc(sizeof(point));
// fill the points with some data for testing
for (int k=0;k<neededPoints;k++) {
outArray[k]->x = k*10;
outArray[k]->y = k*5;
}
// tell the caller the size of the array
*totalPoints = neededPoints;
return 1;
}
int main(int argc, const char * argv[]) {
printf("Program Started\n");
point* arrayOfPoints;
int totalPoints;
createAnArrayOfPoints(&arrayOfPoints,&totalPoints);
for (int j=0;j<totalPoints;j++) {
printf("point #%d is at %d,%d\n",j,arrayOfPoints[j].x,arrayOfPoints[j].y);
}
printf("Program Ended\n");
return 0;
}
My console output looks like this:
Program Started
point #0 is at 0,0
point #1 is at 0,0
point #2 is at 10,5
point #3 is at 0,0
point #4 is at 20,10
Program Ended
What am I doing wrong? I am expecting all 5 points to have values in them..
Thanks.