Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to resize array of struct elements
    text
    copied!<p>I'm writing a program, where I have one class, inside that class ( or outside, hope it doesn't matter ) I have struct. In that class I need to make an array of struct elements ( I know I can use vector e.g. but in program it is only permitted to use simple dynamic arrays ). </p> <p>I declare an array as <code>T * arr[SIZE]</code>, where <code>T</code> is my struct. The only problem is I don't know exact size of array and need to increase it size if necessary. So I wrote function to resize it:</p> <pre><code>if( some cond ){ T * tmpArr[newSIZE]; memcpy( tmp, db, newSIZE*sizeof(T)); delete [] arr; arr = tmpArr; } </code></pre> <p>But I'm getting a error that <code>MyClass::T[....]</code> is incompatible with <code>MyClass::T*[SIZE]</code> which responds to my <code>arr = tmpArr</code> expression I guess.</p> <p>Can you tell me what I'm doing wrong? And how is better to declare <code>T * arr[size]</code> or <code>T * arr = new T[size]</code> and how do I resize ( and free memory from old one ) array in that case? </p> <p>UPDATE:</p> <p>Thanks for answers, I did accordingly in my program:</p> <pre><code> T * tmp = new T[newSIZE]; memcpy( tmp, db, newSIZE*sizeof(T) ); delete [] db; db = tmp; </code></pre> <p>And now I'm getting weird things, after deleting db and assigning <code>db</code> to <code>tmp</code> I try to print all data contained in db ( or tmp ), that weird thing I get:</p> <pre><code> Smith2 Michigan ave▒ ACME, Ltd. One ACME roa▒ Smit▒ Michigan ave` ACME, Ltd. One ACME roa " One ACME road#@"▒▒▒▒Michigan ave`▒▒▒▒Smit▒" ▒▒ ▒8 Ltd.#Michigan avenuemith4▒aF▒ </code></pre> <p>If I print same data before deleting and assigning, I'll get normal text I want. And after in program ( as I didn't have before and maybe that's problem with my code, I get Segmentation fault ). By the way, I'm using <code>struct</code> of <code>std::string</code> and cygwin in my windows. Do you have any idea what's the problem here?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload