CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    Mar 2005
    Posts
    33

    Angry Dynamic array of struct inside a struct

    Hello,

    I am having problem in initializing this : Program is in C++

    struct name
    {
    char s[20];
    }

    struct fruits
    {

    int num;
    struct name *numArray;

    }

    Now if I have two pointer objects for struct fruits, I have to memcpy one struct from the other.

    int num is the indicator of how many elements 'struct name' contains. eg. if num = 3, then numArray has 3 elements.

    i did something like this...

    main()
    {

    fruits *pArr1 = new (fruits*);
    fruits *pArr2 = new (fruits*) {2,{"apple","grapes"};
    int size;

    pArr1->numArray = malloc(sizeof(fruits) * num);

    pArr1 = malloc(sizeof(int) + malloc(sizeof(fruits) * num));

    pArr1 = pArr2;

    }

    Is this okay? I tried to allocate memory for pArr1 and then copied it using = instead of memcpy.. is it a valid approach?

    Thanks,

  2. #2
    Join Date
    Mar 2005
    Posts
    33

    Re: Dynamic array of struct inside a struct

    forgot to include code for deleting the pointers.. but i have doubt in the initialization itself..

  3. #3
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,164

    Re: Dynamic array of struct inside a struct

    That's an interesting bit of coding... It shouldn't compile, and most definitely will not work.

    1) Your calls to new are wrong

    2) Your second call to malloc is wrong and your first call to malloc is missing a cast.

    3)pArr1 = pArr2 assigns the pointer not the contents (that would be *pArr1 = *pArr2)

    4) Why are you trying to make dynamic memory allocations anyway, there is no need for it.

    5) If this is C++, then why is there so much C in it?

    In C++ your code could be reduced to:

    Code:
    #include <string>
    
    class fruit
    {
       fruit(const std::string& name, int quantity)
        :name_(name)
        ,quantity_(quantity)
      {}
    
      const std::string& name() const { return name; }
      int quantity() const { return quantity_; }
    
    private:
      std::string name_;
      int quantity_;
    };
    
    
    int main()
    {
       fruit fruit1("apple", 5);
       fruit fruit2("grapes", 10);
    }
    That said, my interpretation of your code, might not be what you are after.

    Study the class I have written, if you have any questions about it then ask.

    EDIT:
    It would be helpful if you can explain what you are trying to do
    Last edited by PredicateNormative; August 21st, 2011 at 09:54 AM.

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by varsha5in View Post
    Hello,

    I am having problem in initializing this : Program is in C++
    I see very little C++ in the code you posted -- most of it is in 'C' .

    Expanding on PredicativeNormative's code, here is a sample of both using string class and vector instead of using low-level 'C' routines such as malloc().
    Code:
    #include <string>
    #include <vector>
    #include <iostream>
    
    class fruit
    {
      public:
       fruit(const std::string& name, int quantity)
        :name_(name)
        ,quantity_(quantity)
      {}
    
      const std::string name() const { return name_; }
      int quantity() const { return quantity_; }
    
    private:
      std::string name_;
      int quantity_;
    };
    
    
    int main()
    {
       std::vector<fruit> allFruits;
       allFruits.push_back(fruit("apple", 5));
       allFruits.push_back(fruit("grapes", 10));
       
        // print out all the fruits
        for (size_t i = 0; i < allFruits.size(); ++i )
             std::cout << allFruits[i].name() << "  " << allFruits[i].quantity() << "\n";
    
       // create a new fruit object that is equal to the apple object.
       fruit anotherFruit = allFruits[0]; // this is the apple
    }
    Now if I have two pointer objects for struct fruits, I have to memcpy one struct from the other.
    The code above has no pointers, no memcpy(), no need for the user to dynamically allocate memory using malloc() or operator new() and it does exactly the same job your code is trying to do. Also, look at the last line -- I created a new fruit object and made it equal to the apple object I created earlier and placed in the vector.

    Regards,

    Paul McKenzie

  5. #5
    Join Date
    Mar 2005
    Posts
    33

    Post Re: Dynamic array of struct inside a struct

    Sorry for all the above previous code... here is what i need to do..

    I have a struct 'num' that includes struct candybar.. so far this code without the commented lines compiles fine.. but i want to copy the contents from PRIM which is in real a memory address where contents of 'num' lies.. but here as an example I included a set of values. is it possible to do a memcpy for a struct whose contents are defined in a memory address say 0x004DA which is addressed in #define.. here i am using new in this code since the original code on which i m working is partly in c and partly in c++.. so i m open to use either 'new' or malloc..


    #include <iostream>
    #include <cstdlib>
    using namespace std;
    # define PRIM {1,{"chocolate",3.45,23}}


    int main()
    {
    struct candybar
    {
    char bar_name[12];
    float weight;
    short calories;
    };
    struct num
    {
    int index;
    candybar *ncandy;
    };

    num *snacks = new num;
    //num *psnacks;
    snacks->index=1;
    cout<<"val = "<<snacks->index<<endl;
    snacks->ncandy = new candybar[snacks->index];
    //memcpy(snacks),(void *)PRIM,sizeof(candybar)+2);
    //psnacks = (candybar*)PRIM;

    delete []snacks;
    return 0;
    }

  6. #6
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by varsha5in View Post
    Sorry for all the above previous code... here is what i need to do..
    We know what you're trying to do. It's the way you're doing it that is the issue.

    Why does your code have "new" all over the place for no reason? Even so, you're using it incorrectly.
    so far this code without the commented lines compiles fine..
    Compiling fine means nothing. All it means is that the code is syntactically correct. Compiling fine doesn't mean it will work.
    but i want to copy the contents from PRIM which is in real a memory address where contents of 'num' lies.. but here as an example I included a set of values. is it possible to do a memcpy for a struct whose contents are defined in a memory address say 0x004DA which is addressed in #define..
    No.
    Code:
    # define PRIM {1,{"chocolate",3.45,23}}
    It isn't a variable, it is an initializer list. it isn't an l-value where you can take the address of it. So it cannot be used in your memcpy().
    Code:
    #include <cstring>
    
    int main()
    {
      struct candybar
      {
        char bar_name[12];
        float weight;
        short calories;
      };
      struct num
      {
        int index;
        candybar *ncandy;
      };
    
      candybar MyChocolate = {"chocolate", 3.45, 23};
    
      num snacks;
      snacks.index=1;
      snacks.ncandy = new candybar[snacks.index];
      memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
      // etc...
      delete [] snacks.ncandy;
    }
    Regards,

    Paul McKenzie

  7. #7
    Join Date
    Mar 2005
    Posts
    33

    Re: Dynamic array of struct inside a struct

    Hi Paul..

    Is there any other way to copy a struct like I mentioned from a specified memory address.. tht's the situation for me..

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by varsha5in View Post
    Is there any other way to copy a struct like I mentioned from a specified memory address.. tht's the situation for me..
    Unless you're writing a low-level device driver, it is unlikely you'll find anything useful at one particular hard-coded memory address. Perhaps if you elaborated on your goal more we could be of more assistance.

    and then copied it using = instead of memcpy.. is it a valid approach?
    Whether or not operator= does anything useful depends entirely on the types. When two have two pointers, operator= will just copy the memory address, not the data that the pointers are directed at. memcpy() will do so but only for POD types (not for general C++ types).

    The best C++ approach would be to use operator= on the underlying objects rather than pointers, eg *a = *b;, but this requires that the type of A and B have an appropriate operator= defined. The default version is not always good enough.

  9. #9
    Join Date
    Mar 2011
    Location
    Washington D.C.
    Posts
    44

    Re: Dynamic array of struct inside a struct

    I study the code which is Paul McKenzie's last post and add only couts at last. That's it:

    Code:
    #include <cstring>
    #include <iostream>
    int main()
    {
        using namespace std;
      struct candybar
      {
        char bar_name[12];
        float weight;
        short calories;
      };
      
      struct num
      {
        int index;
        candybar *ncandy;
      };
    
      candybar MyChocolate = {"chocolate", 3.45, 23};
    
      num snacks;
      snacks.index=1;
      snacks.ncandy = new candybar[snacks.index];
      memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
      
      cout <<  snacks.ncandy[0].bar_name;
      cout << "\n";
      cout <<  snacks.ncandy[0].weight;
      cout << "\n";
      cout <<  snacks.ncandy[0].calories;
      cout << "\n";
      // etc...
      delete [] snacks.ncandy;
      system("PAUSE");
      return 0;
    }
    Output is:

    Code:
    chocolate
    3.45
    23


    I don't understand some points. Firstly when i research memcpy on the web, i find this.

    It's from http://www.cplusplus.com/reference/c...string/memcpy/
    Code:
    /* memcpy example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char str1[]="Sample string";
      char str2[40];
      char str3[40];
      memcpy (str2,str1,strlen(str1)+1);
      memcpy (str3,"copy successful",16);
      printf ("str1: &#37;s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
      return 0;
    }
    as you see below, first and second parameters are string so that's no problem.

    Code:
    memcpy (str2,str1,strlen(str1)+1);
    memcpy (str3,"copy successful",16);

    However , in the McKenzie's code

    Code:
    memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
    first parameter is a string and second parameter is an object of a structure. Our first paramater is only bar_name. However, Not only we assign ncandy's barname, but also we assign ncandy's weight and calories at the same time. How did it happen??

    Secondly,

    Code:
    snacks.index=1;
    snacks.ncandy = new candybar[snacks.index];
    after new candybar we use [] and snack.index inside of it.Why ??What is our prupose doing it?And we assign snack.index to 1. Why 1 ? Is it a random assignment?
    Last edited by loves_oi; August 22nd, 2011 at 05:52 PM.

  10. #10
    Join Date
    Mar 2005
    Posts
    33

    Re: Dynamic array of struct inside a struct

    yes i m looking for writing low level coding.. tht's why i want to copy it from a particular memory address.. i think i almost found the way to do it.. will post it as soon as i test it..

  11. #11
    Join Date
    Mar 2011
    Location
    Washington D.C.
    Posts
    44

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by loves_oi View Post
    I study the code which is Paul McKenzie's last post and add only couts at last. That's it:

    Code:
    #include <cstring>
    #include <iostream>
    int main()
    {
        using namespace std;
      struct candybar
      {
        char bar_name[12];
        float weight;
        short calories;
      };
      
      struct num
      {
        int index;
        candybar *ncandy;
      };
    
      candybar MyChocolate = {"chocolate", 3.45, 23};
    
      num snacks;
      snacks.index=1;
      snacks.ncandy = new candybar[snacks.index];
      memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
      
      cout <<  snacks.ncandy[0].bar_name;
      cout << "\n";
      cout <<  snacks.ncandy[0].weight;
      cout << "\n";
      cout <<  snacks.ncandy[0].calories;
      cout << "\n";
      // etc...
      delete [] snacks.ncandy;
      system("PAUSE");
      return 0;
    }
    Output is:

    Code:
    chocolate
    3.45
    23


    I don't understand some points. Firstly when i research memcpy on the web, i find this.

    It's from http://www.cplusplus.com/reference/c...string/memcpy/
    Code:
    /* memcpy example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char str1[]="Sample string";
      char str2[40];
      char str3[40];
      memcpy (str2,str1,strlen(str1)+1);
      memcpy (str3,"copy successful",16);
      printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
      return 0;
    }
    as you see below, first and second parameters are string so that's no problem.

    Code:
    memcpy (str2,str1,strlen(str1)+1);
    memcpy (str3,"copy successful",16);

    However , in the McKenzie's code

    Code:
    memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
    first parameter is a string and second parameter is an object of a structure. Our first paramater is only bar_name. However, Not only we assign ncandy's barname, but also we assign ncandy's weight and calories at the same time. How did it happen??

    Secondly,

    Code:
    snacks.index=1;
    snacks.ncandy = new candybar[snacks.index];
    after new candybar we use [] and snack.index inside of it.Why ??What is our prupose doing it?And we assign snack.index to 1. Why 1 ? Is it a random assignment?
    ??

  12. #12
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by loves_oi View Post
    However , in the McKenzie's code

    Code:
    memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
    first parameter is a string and second parameter is an object of a structure.
    That is a mistake. It should be this:
    Code:
    memcpy(snacks.ncandy[0], &MyChocolate, sizeof(candybar));
    after new candybar we use [] and snack.index inside of it.Why ??What is our prupose doing it?
    You are using array new[] to allocate the memory.
    And we assign snack.index to 1. Why 1 ?
    It could be 100, it doesn't make a difference. Obviously it's only an example.

    Do you understand what array new[] does? If you do, then the code should be obvious.

    Regards,

    Paul McKenzie

  13. #13
    Join Date
    Mar 2011
    Location
    Washington D.C.
    Posts
    44

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by Paul McKenzie View Post

    That is a mistake. It should be this:

    Code:
    memcpy(snacks.ncandy[0], &MyChocolate, sizeof(candybar));
    Regards,

    Paul McKenzie
    Interestingly , No it is not a mistake .When i compile and run with this:

    Code:
    memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
    outputs is:
    Code:
    chocolate
    3.45
    23
    Thus,It is certainly true according to outputs,isn't it?


    However,When i change the code as below:

    Code:
    memcpy(snacks.ncandy[0], &MyChocolate, sizeof(candybar));
    I take such an error:
    24 C:\Users\loves_oi\Desktop\deneme.cpp cannot convert `main()::candybar' to `void*' for argument `1' to `void* memcpy(void*, const void*, size_t)'

    ??
    Last edited by loves_oi; August 23rd, 2011 at 08:34 AM.

  14. #14
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Dynamic array of struct inside a struct

    Quote Originally Posted by loves_oi View Post
    Interestingly , No it is not a mistake .When i compile and run with this:

    Code:
    memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar));
    outputs is:
    Code:
    chocolate
    3.45
    23
    Thus,It is certainly true according to outputs,isn't it?

    However,When i change the code as below:

    Code:
    memcpy(snacks.ncandy[0], &MyChocolate, sizeof(candybar));
    I take such an error:
    24 C:\Users\loves_oi\Desktop\deneme.cpp cannot convert `main()::candybar' to `void*' for argument `1' to `void* memcpy(void*, const void*, size_t)'

    ??
    Just because the output is what you want doesn't mean the code is correct.

    In this case, the first one is coincidentally working because bar_name happens to be the first member of the candybar struct in memory. Therefore, the address of the bar_name field within that object happens to be the same as the address of the object. But it isn't the best approach to rely on that, because you cannot be certain this will always be the case.

    Paul's attempt to fix the code was still not entirely correct either; he intended to specify the address of the candybar object, but instead specified the object itself. The corrected code would be
    Code:
    memcpy(&snacks.ncandy[0], &MyChocolate, sizeof(candybar));
    However, as I said earlier, memcpy() is a very "C" way of doing things and while it will work in this particular case, in general it is better to define the operator= for the candybar type and use that for copying.

  15. #15
    Join Date
    Mar 2011
    Location
    Washington D.C.
    Posts
    44

    Re: Dynamic array of struct inside a struct

    ok. I understand. Thanks a lot.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured