Re: why does this happen?

From: hk_mp5kpdw (andrew_a_hanson_at_msn.com)
Date: 03/29/05


Date: 29 Mar 2005 12:07:48 -0800


> test_t is a c structure but sontaing the STL string.
> In may data I cannot use new yet because of all these structures.
> So malloc is creating the memory but it does not initialize the
string path
> because it was done by malloc instead of new.

structs are a part of C++ just as much as they are in C. It is just
that typically you see classes being talked about and used much more
than structs. Bottom line, structs DO EXIST IN C++. You should have
no problem using new even when allocating memory for a struct. A
struct can even have member functions (including constructors and
destructors typically associated with a class).

> Is there any way around this?

Use "new":

#include <string>

using namespace std;

typedef struct test
{
   string path;
   int val;
   test(const string& p) : path(p) {}
} test_t;

typedef test_t *test_p;

test_p foo(const string& path)
{
    test_p temp = new test_t(path);
    if( temp ) return temp;
    else return NULL;
}

int main(void)
{
   test_p tp = foo("abcd");
   return 0;
}



Relevant Pages

  • Re: A taxonomy of types
    ... IMO, some kind of "signature" representation is much more general purpose, ... as a union of C types, and/or structs, and/or typedef's. ... OTOH a string can be treated as a string, ...
    (comp.lang.misc)
  • DataGrid.DataSource and binding
    ... I would like to use a collection of structs like the ones below as the ... DataSource for a DataGrid: ... In the documentation of Binding ...
    (microsoft.public.dotnet.framework.windowsforms)
  • Re: Data type. Multi pair of values. How can I do this?
    ... For each item the first value is a string and the second value is an ... Enum named Country. ... public struct CityInfo ... Structs are good when you need lightweight objects, like here for logical grouping of attributes. ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: whats wrong with my program ?
    ... ConstructTime(). ... Third, this sets the structs to all-bits-zero, not to sensible initial ... Note also that asctimereturns a pointer to a static array, ... the string written by the first. ...
    (comp.lang.c)
  • Re: Kurzinitialisierer =?ISO-8859-15?Q?f=FCr_struct?=
    ... Wenn man einen String einer Methode übergibt, ... neuer Verweis angelegt. ... Ausserdem wäre es unzutreffend zu sagen, dass structs keine ... Verweistypen implementiert sind. ...
    (microsoft.public.de.german.entwickler.dotnet.csharp)