im trying to create a class type structure using struct instead of classes i dont know what im doing wrong i have one working code and i have some thing
else im working on.
working
im trying to do the same thing only using arrays instead. the program malfunctionCode:#include <iostream> #include <stdlib.h> using namespace std; struct myclass { int * array; int nelements; }; struct myclass constructor(struct myclass n,int size) { int * array = NULL; array = (int *)malloc(size * sizeof(int)); if(array == NULL) { cerr << "memory could not be allocated." <<endl; }else { cout << "memory allocated." <<endl; } n.array = array; n.nelements = size; return n; } void initializeobjects(int * array,int size) { for(int i = 0; i < size; i++) array[i] = rand() % 100 + 1; } void printobjects(int * array,int size) { for(int i = 0; i < size; i++) { cout << " value " <<array[i] << endl; } } int main() { struct myclass m; m.nelements = 12; m = constructor(m,m.nelements); initializeobjects(m.array,m.nelements); printobjects(m.array,m.nelements); system("pause"); return 0; }
guess what im asking is using the pointer in theCode:#include <iostream> using namespace std; struct myclass { int array[]; //size not defined int nelements; }; void constructor(int * array,int size) { array = NULL; array = (int *)malloc(size * sizeof(int)); //size defined here } void initializeconstrut(int * array,int size) { for(int i = 0; i < size; i++) array[i] = i; } void print(int * array,int size) { for(int i = 0; i < size; i++) { cout << " value " <<array[i] << endl; } } int main() { struct myclass m; m.nelements = 12; constructor(m.array,m.nelements); initializeconstrut(m.array,m.nelements); print(m.array,m.nelements); system("pause"); return 0; }
first code section better or is there another way'
i dont know about making the second code work.
thanks and best regards.




Reply With Quote
