-
July 26th, 2009, 09:45 AM
#1
Correct way to pass a pointer to a structure
Hi
This problem is driving me crazy
#include "stdafx.h"
#include "fstream.h"
struct myStruct {
int a;
int b;
} *myStruct_;
void tryToInitialiseArray(myStruct *ms);
int main(int argc, char* argv[])
{
myStruct_ = NULL;
tryToInitialiseArray(myStruct_);
cout << myStruct_[0].a << endl;
printf("Hello World!\n");
return 0;
}
void tryToInitialiseArray(myStruct *ms) {
ms = new myStruct[3];
ms[0].a = 1;
ms[0].b = 11;
ms[1].a = 2;
ms[1].b = 22;
ms[2].a = 3;
ms[3].b = 33;
}
This small program exhibits the problem that I am having.
I have a pointer to a struct, which I want to initilise (new) in a function.
It compiles okay - and runs, but crashes at the 'cout'. Running in Debug you can see that after the call to tryToInitialiseArray, myStruct_ is still NULL.
I guess this is because the myStruct_ is being passed by copy (not as a pointer or reference) - but I don't understand why.
Can anybody help?
(I have also tried it without the 'struct" in the function definition, with the same results.
Thx
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|