ms = &local_ms;
This modifies the local pointer ms
to point to the other local pointer to the allocated structure. However, what you want is to modify the caller's pointer. ms
is a pointer to that, so you want to modify the thing that ms
points to:
*ms = local_ms;
But this isn't C, so you could use simpler reference semantics:
void newStruct ( myStruct *& ms, int x)
// ^^ reference to pointer
{
// ...
ms = local_ms;
}
// usage
myStruct * ms;
newStruct(ms, 42);
But the language (C or C++) gives a cleaner way to return a value from a function: you can return a value from the function.
myStruct * newStruct(int x)
{
// ...
return local_ms;
}
// usage
myStruct * ms = newStruct(42);
But in C++, we can use constructors, rather than arbitrary functions, to initialise new objects:
struct myStruct { // no need for that typedef nonsense
explicit myStruct(int n) :
n(n),
anArray(new char[n]) // sizeof(char) is 1 by definition
{}
int n;
char *anArray; // * goes before the variable name
};
// usage
myStruct ms(42); // don't use `new` unless you really need it
Now just one thing is missing: anArray
is never deleted, giving a memory leak. The simplest fix is to use a dynamic array type from the standard library: either string
or vector
.
struct myStruct {
explicit myStruct(int n) : n(n), anArray(n) {}
int n;
std::string anArray;
};
But of course, n
is now redundant; you should get rid of it and use anArray.size()
instead. This means that the structure itself is pretty pointless; you just need
std::string ms(42);