Array of pointers to structs - c++

EDIT: Im quite new to c++ and programming as a whole.
I'm supposed to make a program where i use stucts and and an array of structs.
Security council < > Member of Security council
My task was to use the concept of "UML aggregation" to create a program where I use structs and struct arrays. (I hope you understand what I'm trying to say)
Since a Member of a Security council is a part of a Security council, and not the other way around, the struct of Security council must have an array of its members.(bear with me)
//example
struct Member_sc{
char * name;
int age;
};
struct Security_council{
Member_sc members[10];
};
Now, I've created this program and everything works perfectly (according to my teacher), but now she told me create an exact copy, but instead of the "members" array I must use an array of pointers to the Member_sc structs. Since I havent completely figured out how pointers work, I have come across some problems.
I can post the code to the original program if needed, but it contains 4 files(main, header, and some function files) and it would be a pain to try and post it here.
here is the prototype (all in one file, for now)
#include <iostream>
using namespace std;
struct member_sc{
string name;
};
struct security_council{
member_sc *point;
security_council **search; // ignore this for now
int n;
security_council():n(0){}
};
void in_mem( member_sc &x){
getline(cin,x.name);
}
void out_mem(member_sc &x){
cout<<x.name<<endl;
}
void in_SC(security_council &q, member_sc &x){
int num; //number of members
cin>>num;
for(int i=0; i<num; ++i){
in_mem(x);
q.point[q.n]=x;
q.n++;
}
}
void out_SC(security_council &q,member_sc &x){
for(int i=0; i<q.n; ++i){
out_mem(q.point[i]);
}
}
int main(){
member_sc y;
security_council x;
in_mem(y); // works
out_mem(y); // works
in_SC(x,y); // crashes after i input the number of members i want
out_SC(x,y); //
system("pause");
return 0;
}
The program crashes after you input the number of members you want in your Security council.
Is my way of thinking right? or should I use dynamic memory allocation?
in addition to that (my teacher gave me an additional task) create a search function using pointers. i thought that pointer to pointer may be good for that, but im not sure.
Any help or advice would be greatly appreciated.
( i think ill figure out the search thingy once i figure out how pointers to structs work)

The first part of your issue is this:
cin >> num;
this reads only the digits that have been typed and stops at the newline. Then, in in_mem the call to getline immediately reads a newline. You need to do:
cin >> num;
cin.ignore();
this will drain the input stream of any remaining input, or catch up so to speak.
However your core problem is that you don't allocate any memory for "point" to point to.
A pointer is just a variable holding a value that happens to be the address (offset from 0) of a thing in memory. If you are going to the airport and write "Gate 23" on a post-it note, the post it note is a pointer and "Gate 23" is the value.
In your code, that variable is uninitialized and will either be 0, if you are lucky, or some random address in memory if you aren't so lucky.
To the airport analogy: you arrive at the airport and find that your post-it note has "pizza" written on it. Not helpful.
Your teacher has actually specified an "array of pointers". Break that down: pointer to what? member_sc, that's member_sc*. And now make it an array
member_sc* pointers[10];
NOTE: This is not good, modern C++ - in modern C++ you would use something called a smart pointer (std::unique_ptr) probably.
std::unique_ptr<member_sc[]> pointers(new member_sc[10]);
Now you have 10 pointers instead of just one, and all of them will need some allocation to point to. The easiest way to do this is with the new keyword and the copy constructor:
for (int i = 0; i < num; i++) {
in_mem(x);
pointers[q.n] = new member_sc(x); // make a clone of x
q.n++;
}
or in modern C++
for (int i = 0; i < num; i++) {
in_mem(x); // x is temporary for reading in
pointers[q.n] = std::make_unique<member_sc>(x);
q.n++;
}
However there is a limitation with this approach: you can only have upto 10 security council members. How do you work around this? Well, the modern C++ answer would be to use a std::vector
std::vector<member_sc> members;
// ditch n - vector tracks it for you.
// ...
for (int i = 0; i < num; ++i) {
in_mem(x);
q.members.push_back(x);
// q.n is replaced with q.members.size()
// which is tracked automatically for you
}
but I'm guessing your teacher wants you to actually understand pointers before you get to forget about them with modern luxuries.
We need to re-use the pointer stuff we've just used above and change "pointers" to an array of pointers.
Which means we're going to want a pointer to a set of pointer-to-member_sc.
member_sc** pointers;
We'll need to assign some memory for this to point to:
cin >> num;
cin.ignore();
if (num == 0) {
// do something
return;
}
pointers = new member_sc[num];
luckily, using a pointer to an array is as easy as using an array, the only major difference being that you lose the size-of-array information -- all you have is the address, not the dimensions.
for (int i = 0; i < num; i++) {
in_mem(x);
q.pointers[i] = new member_sc(x);
q.n++;
}
I'm deliberately not providing you with a complete working example because this is obviously for a class.

You never initialize the memory that the point member refers to, yet then in statement q.point[q.n]=x; you attempt to use it.
Basically, after you read in the number of members, and before the for loop where you read in the individual members, you need to allocate an array of an appropriate number of member_sc objects and store it in q.point. Don't forget to free this memory when done using it.
Once you do that, you can also remove the member_sc &x argument from both in_SC and out_SC, as that will become unnecessary.
Finally, some validation of your input seems to be in place. Consider what will happen if the user enters a negative number, and you attempt to use that directly to determine the size of memory to allocate.
Here's a simple example showing how to use a dynamically allocated array of structures:
#include <iostream>
#include <string>
struct member_sc {
std::string name;
};
void test_array(int count)
{
if (count <= 0) {
return; // Error
}
// Allocate an array of appropriate size
member_sc* members = new member_sc[count];
if (members == nullptr) {
return; // Error
}
// ... fill in the individual array elements
for(int i(0); i < count; ++i) {
// ... read from input stream
// I'll just generate some names to keep it simple
members[i].name = "User A";
members[i].name[5] += i; // Change the last character, so we have different names
}
// Now let's try printing out the members...
for(int i(0); i < count; ++i) {
std::cout << i << ": " << members[i].name << "\n";
}
delete[] members;
}
int main(int argc, char** argv)
{
for(int count(1); count <= 10; ++count) {
std::cout << "Test count=" << count << "\n";
test_array(count);
std::cout << "\n";
}
return 0;
}
Example on Coliru
Of course, there are many other issues with this style of code, but I believe that's beside the point of this question. For example:
Instead of using bare pointers, it would be more appropriate to use some kind of a smart pointer.
Instead of a simple array, use some kind of collection, such as a vector.

Since you are asked to use an array of pointers, do so: replace
Member_sc members[10];
with
Member_sc* members[10];
Then fill out that array using dynamic memory allocation. As a matter of good form, at the end of the program remember to release the dynamic memory you have used.

Related

What the error in my code. I try to use array in class but getting logical error

I try to make an array and take input and then simply showing the output on the screen but uses classes and objects, Here is my code:
#include<iostream>
using namespace std;
class array{
int ar[], n;
public:
void input();
int display();
}obj;
void array::input(){
cout<<"Enter item size: ";
cin>>n;
int ar[n]={};
for(int i=0; i<n; i++){
cout<<"Enter value at index "<<i<<" : ";
cin>>ar[i];
}
}
int array::display(){
cout<<"You Entered: ";
for(int i=0 ; i<n; i++){
cout<<ar[i];
}
}
int main(){
obj.input();
obj.display();
}
In the sample run, I entered 1 and 2 and I am expected to get 1 and 2.
Two problems in your code.
First int ar[] should not compile. I get the following error:
prog.cc:4:12: error: ISO C++ forbids flexible array member 'ar' [-Wpedantic]
int ar[], n;
^
Next, in array::input() you create a completely new array int ar[n]={}; which is also not valid c++. Array sizes must be compiletime constants. Moreover, this array shadows the member and is unrelated to it (apart from having the same name). So this ar is gone once you return from the method. You never write anything into the member ar.
If you dont know the size in advance you should use a std::vector:
#include <iostream>
#include <vector>
class array{
std::vector<int> ar;
public:
void input();
int display();
};
void array::input(){
std::cout << "Enter item size: ";
int n;
std::cin >> n;
ar.resize(n);
for(int i=0; i<n; ++i){
std::cout << "Enter value at index " << i << " : ";
std::cin >> ar[i];
}
}
int array::display(){
std::cout<<"You Entered: ";
for(int i=0 ; i<n; ++i){
std::cout << ar[i];
}
}
int main() {
array obj;
obj.input();
obj.display();
}
PS: read here why using namespace std; is bad practice: Why is "using namespace std" considered bad practice?
IMHO user463035818s answer is sufficient, but for all that OP asked me
how to fix this compiler issue.
The recommended fix would be by design i.e. like shown in user463035818s answer.
So, I want to elaborate how to fix the sample code of OP (with "minimal" changes). That might make obvious why user463035818s answer is the better one. (I repeated the link three times – it should be clear to everybody that I consider this as the better solution.)
The actual compiler error (or warning or feature accepted by compiler extension):
OP used int ar[] a C array as class member without denoting the size.
This is called Flexible array member but it is a C99 feature (not supported by the C++ standard).
The linked Wikipedia article provides a nice example:
struct vectord {
size_t len;
double arr[]; // the flexible array member must be last
};
To be clear, flexible array members don't provide automatic allocation. They just represent an array of arbitrary length. The programmer is responsible to grant sufficient storage for that array. Hence even in C, and with the resp. syntax adjustments, this code would have been broken.
Some C++ compilers adopt features from C as (proprietary) extension. That's the reason that OP got responses ranging from "On my side, it works."1 to "This is a compiler error." However, I would consider usage of such extensions as bad style in general. With different compiler settings or a different compiler, this might not work anymore.
1 This is not the only issue of OPs code. "It works" might be merely bad luck. OPs code has Undefined Behavior. One kind of Undefined Behavior is "It works" which is not the best one because programmer might believe that the code is fine.
A lot of higher level languages (Java, C#, Python) tries to cover memory allocation and storage management "under the hood" completely because it's not quite easy to make this always correct and consider every edge case sufficiently. This might cause an additional performance impact for the administration of memory. In C and C++, the programmer has ful control over memory allocation. It's both a blessing and a curse.
The standard library of C++ provides a variety of tools to make programmers allocation life easier.
For dynamic arrays, the tool of choice is the template class std::vector. It provides an overloaded operator[] which allows that it can be accessed just like an array. It provides methods like reserve() and resize(). The storage is internally managed.
I would strongly recommend to use std::vector but there is also the possibility to do it using new[] and delete[].
For this, the class array might look as follows:
class array {
int *ar; // a raw pointer for storage
int n; // the current size of array
public:
int display();
int* and int are plain old data types → implicit construction leaving them uninitialized. So, there really should be defined at least a default constructor.
array(): ar(nullptr), n(0) { }
The input() method has to ensure proper storage.
void input()
{
// release old memory (if there is one)
delete[] ar; ar = nullptr; n = 0;
// input
std::cout << "Enter item size: ";
std::cin >> n;
if (n <= 0) return;
ar = new int[n];
for (int i = 0; i < n; ++i) {
std::cout << "Enter value at index " << i << ": ";
std::cin >> ar[i];
}
}
When an instance of class array is deleted it should release the internal storage. Otherwise, the allocated memory pointed by ar will be orphaned and lost until process is terminated by OS. Such lost memory is called memory leak.
~array() { delete[] ar; }
Please, note that calling delete[] (or delete) with a nullptr is valid. Hence, no extra if (ar) is needed.
Finally, we have to obey the Rule of three. The compiler generates implicitly copy constructor and copy assignment operator which will copy the class array members by value. Copying a pointer by value does not mean that the contents (it points to) is copied. It just means copy the pointer (address value). Hence, an (accidental, unintended) copy of class array could result in two instances of class array which members ar point to the same memory. Once, one of them deletes that memory, the ar of the other becomes dangling i.e. points to released memory. (Bad!) If the other instance is destroyed also it will delete[] ar again. This is double deleting which is prohibited. (Bad again!)
One option could be to define copy constructor and copy assignment to handle this appropriately by making a deep copy of ar contents (with another new[]). However, if copy is not intended, an alternative is to just explixitly prohibit copy for class array:
array(const array&) = delete;
array& operator=(const array&) = delete;
};
Putting this althogether in array.cc:
#include <iostream>
class array {
int *ar; // a raw pointer for storage
int n; // the current size of array
public:
array(): ar(nullptr), n(0) { }
~array() { delete[] ar; }
array(const array&) = delete;
array& operator=(const array&) = delete;
void input();
void display();
};
void array::input()
{
// release old memory (if there is one)
delete[] ar; ar = nullptr; n = 0;
// input
std::cout << "Enter item size: ";
std::cin >> n;
if (n <= 0) return;
ar = new int[n];
for (int i = 0; i < n; ++i) {
std::cout << "Enter value at index " << i << ": ";
std::cin >> ar[i];
}
}
void array::display()
{
std::cout << "You Entered: ";
for (int i = 0; i < n; ++i) {
std::cout << ar[i];
}
std::cout << '\n';
}
int main()
{
array obj;
obj.input();
obj.display();
return 0;
}
Compiled and tested:
$ g++ -std=c++11 -Wall -pedantic array.cc && ./a.out
Enter item size: 1↲
Enter value at index 0: 2↲
You Entered: 2
$
Live Demo on coliru
The last sentence in OPs question is a bit unclear for me (although I assume it's just bad worded):
In the sample run, I entered 1 and 2 and I am expected to get 1 and 2.
Either input is 2 1 2 then output is 1 2.
Or input is 1 2 then output is 2.
Please note that array::input() expects first input of array::n but array::display() doesn't output array::n.

Cannot convert char to char*[] and illegal sizeof operand

I am trying to read from a file and put each new line/entry in to an array. However, I am more primarily familiar with C# and C++ isn't my thing. The reason I need to do this is for a project and I am the only one that is willing to do this part.
I do not know how to properly convert character types or if it is possible. I have tried searching around the internet but have not found any answers regarding something like my issue here. Also, because I do not know what causes an illegal sizeof operand I do not know what is wrong here.
#include "..\STDInclude.h"
// TODO: Fill that list with names
char* Bots::NameList[] = {};
void Bots::GetNames()
{
using namespace std;
ifstream file("bot_names.txt");
if (file.is_open())
{
for (int i = 0; i < 48; i++)
{
file >> Bots::NameList[i];
}
}
}
void Bots::Initialize()
{
// Replace staff array with custom one
*(char***)Addresses::BotArray1 = Bots::NameList;
*(char***)Addresses::BotArray2 = Bots::NameList;
*(char***)Addresses::BotArray3 = Bots::NameList;
// Apply new array size
int size = (sizeof(Bots::NameList) / sizeof(Bots::NameList[0]));
*(BYTE*)Addresses::BotArraySize1 = size;
*(BYTE*)Addresses::BotArraySize2 = size;
*(BYTE*)Addresses::BotArraySize3 = size;
*(BYTE*)Addresses::BotArraySize4 = size;
}
Arrays in C++ are of fixed size. So when you write char* Bots::NameList[] = {} , you have an empty array of c-strings (aka char*).
Worse, when you later write file >> Bots::NameList[i]; you are writing null terminated c-strings to uninitialized pointers, which will cause memory corruption.
Unless fundamental rewrite, this code is doomed to fail. I strongly suggest that you replace use of char* with std::string and that you switch from fixed size arrays to vectors.
std::vector<std::string> Bots::NameList;
void Bots::GetNames()
{
...
for (int i = 0; i < 48; i++)
{
string s; // space separated strings ? sure ?
file >> s; // or getline(file, s) if you want lines
NameList.push_back(s);
}
}
}
Aditional remark:
I can't tell for sure, as I don't know the definition of Addresses members, but statements like the following are relatively suspicious:
*(char***)Addresses::BotArray1 = Bots::NameList;
It suggests that Addresses::BotArray1 is an array or a pointer. But the fact that you are casting with (char***) suggest that you tried to fix a type mismatch. And dereferencing the casted pointer will make sense only if BotArray points already to a valid char** pointer in which the address of NameList should be stored.
In C++ an array must be sized when created and then it is fixed, so char* Bots::NameList[] = {}; is a zero element array and is stuck that way. Worse, in file >> Bots::NameList[i] nothing ever allocated storage for Bots::NameList[i], so your program is writing into uninitialized memory. Probably a BOOM waiting to happen. I'm going to suggest something completely different.
in the Bots class definition:
std::vector<std::string> NameList;
Then later...
void Bots::GetNames()
{
std::ifstream file("bot_names.txt");
if (file.is_open())
{
for (int i = 0; i < 48; i++)
{
std::string temp;
file >> temp;
NameList.push_back(temp);
}
}
}
Addresses::BotArray1..N must also become std::vectors and Addresses::BotArraySize1..N are made redundant because vectors know their size.

Program crashes when running this function

I'm having trouble with wrapping my head around pointers, and using pointers in structs. To start, I don't know if I am using the pointer properly in the struct. Additionally, when I run my program, it seems to crash when it reaches readRecords, so there must be something wrong with it. Since I don't quite know how to use pointers very well, I am probably doing something wrong here... I just don't know what. Is there some way that I can edit this function so that I don't get crashes? Also, I have to keep these functions, as they are part of my project requirements.
struct testScores
{
string name;
string idNum;
int testNum;
int *tests; // This is supposed to be a dynamically allocated array
double average;
char grade;
};
[...]
void arrStruct(testScores*& sPtr)
{
sPtr = new testScores[];
}
void readRecords(ifstream& data, int record, testScores*& sPtr)
{
for (int count = 0; count < record; count++)
{
data >> sPtr[count].name;
data >> sPtr[count].idNum;
data >> sPtr[count].testNum;
sPtr[count].tests = new int[sPtr[count].testNum]; // tests is dynamically allocated (?)
for (int tCount = 0; tCount < sPtr[count].testNum; tCount++)
data >> sPtr[count].tests[tCount];
}
}
sPtr = new testScores[];
This appears to be illegal syntax - array new requires a subscript to know how much space to allocate.
Usually this is at least 1, in your case the compiler probably interprets this as new testScores[0] which does return a valid pointer, but without allocating any memory from the heap.
Of course any subsequent access to memory pointed to by sPtr is out-of-bounds and causes undefined behaviour (in your case a crash).

Passing array of objects to a class

#include "average.c++"
#include "name.c++"
class Grade {
public:
Grade() {}
void searcharray(Name *array[]) {
int i;
for(i = 0; i <= 10; i++){
printf("%s", array->name);
}
}
};
int main() {
int i;
char line[64];
Name *names[10];
for(i = 0; i < 5; i++){
scanf("%s", &line);
names[i] = new Name(line);
}
Grade *test;
test = new Grade();
test->searcharray(names);
}
This code gives the error
"grade.c++ in member function 'void Grad::searcharray(Name*)':
grade.c++:11:25: error: request for member 'name' in ' array', which is of pointer type 'Name*' (maybe you meant to use '->' ?)"
I need help making this work. I am guessing it is something simple like extending the class like you would in Java but not sure how this works in c++.
I am assuming you can pass an array of objects to a class like you would in C with just an array.
The root to my question is to find a solution and to get a reason for this code being wrong.
Your code can be substantially improved by taking advantage of the Standard library. The problem with your initial code was that you were doing array->name where array was a C-style array (technically the pointer into which it decayed). An expression like that isn't possible unless you obtain the pointer at the index first:
array[i]->name;
Moreover, the for loop in which that line was written is traversing the array 1 too many times. The conditional statement i <= 10 should be i < 10 so you won't dereference an address past the end of the array.
Anyway, instead of showing your code with the corrections, I thought I might as well show you what it should look like if you use vectors, memory-management, and std::string. I hope this helps:
#include <iostream>
#include <string>
#include <vector>
#include <memory>
class Grade
{
public:
Grade() { }
static void searcharray(const std::vector<std::unique_ptr<Name>>& array)
{
for (const auto& obj : array)
{
std::cout << obj->name;
}
}
};
int main()
{
std::string name;
std::vector<std::unique_ptr<Name>> names;
while (std::cin >> name)
names.push_back(std::unique_ptr<Name>(new Name(name)));
// names.push_back(std::make_unique<Name>(name))
Grade::searcharray(names);
}
Note that I also made searcharray static since it has nothing to do with a given instance of Grade.
As others have pointed out the problem is that you're using a parameter declared Name *array[] like array->name.
Remember that C++ built on top of C, which follows a rule 'declaration mimics use', which means that the way a variable is declared looks like the way it is used. So with the declaration:
Name *array[]
The way you get a name out of this is:
*array[i]
And name is a member of Name so you have to get a Name object first. Then you can tack on member access:
(*array[i]).name
And then you can use the -> shortcut where (*x).y is the same as x.y:
array[i]->name
Other issues:
Your code appears to be heavily influenced by the style of code required for the 1989 or 1990 version of C. You should try to avoid that as it makes writing C++ code much worse than it has to be.
You declare a Grade * and allocate it immediately. You can combine the declaration with initialization into:
Grade *test = new Grade();
But you don't need to use a pointer anyway: use Grade test; (and if you did need a pointer then you should use a smart pointer. Never use 'naked' new.)
Similarly you can avoid new when you create Names.
Name names[10]; // assuming that Name is default constructible
for(...) {
...
name[i] = Name(line);
}
You should avoid a fixed size array here. Instead you should default to using std::vector:
std::vector<Name> names;
for (...) {
...
names.push_back(Name(line)); // or in C++11 names.emplace_back(line);
}
You should declare the variable i as part of the for loop, not as a variable outside it:
for (int i=0; i<10; ++i)
When you read input you should avoid scanf and fixed sized buffers. Instead, if you're reading lines you should probably start off with std::getline and std::string.
std::string line;
while (std::getline(std::cin, line)) { // read as many lines as there are, not just 10 no matter what
names.emplace_back(line);
}

Resizing a dynamically allocated array passed by reference

I am stuck in this problem: how to resize, inside a function, a dynamically allocated array, which has been passed, to the function, by reference.
I tried this, along with countless variations on this very approach. Of course this is just an example, it should print "john" ten times, expanding an array passed by reference that originally had only size 1 ( ie only 1 name ).
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int NumLast=-1;
int Surname(string *MyData)
{
for (int i=0; i<10 ; i++)
{
NumLast++;
string *Temp = new string[NumLast+1]; // temporary array
for (int jjj=0; jjj<NumLast; jjj++)
Temp[jjj]=MyData[jjj];
delete[] MyData;
MyData=Temp;
MyData[NumLast]="John";
}
return 0;
}
void main()
{
string *Data = new string[1]; // inizializza l'array
Surname(&*Data);
for (int iii=0; iii<10; iii++)
cout << Data[iii] << endl;
system("pause");
}
You have to pass by reference. You are passing by value. You are getting
&*Data = Data
The value of the address of what is pointed to Data = Data
Then you pass it by value to Surname. Anything Surname does to it won't affect Data in main.
int Surname(string *MyData) // This will take a copy of whatever you passed in to MyData
should be (The reference operator should be on the function definition.)
int Surname(string*& MyData)
^^
And the call will be
void main()
{
string *Data = new string[1];
Surname(Data); // The function will take a reference of data.
Buy may I ask why you are allocating in a loop?
Looks like std::vector is best solution for your case.
If you really need to reallocate manually, think about old school malloc(), free(), realloc() interface. Main thing to remember is to not intermix it with C++ new/delete interface despite usually new / delete is implemented using malloc() / free().
If you need array you should pass not array but pointer (or reference) to array (double pointer). In case of std::vector it is enough to pass reference to it.
Yet another argument to use reference to std::vector - in case of pointer to array caller should be notified somehow what is new array size.
I decided to try and go through your code line by line and point out some of the issues and highlight what's going on. I will start from your main function:
void main()
{
string *Data = new string[1]; // inizializza l'array
Surname(&*Data);
for (int iii=0; iii<10; iii++)
cout << Data[iii] << endl;
}
OK, so what this code does is allocate one string and save the pointer to it in a variable called Data.
Then it dereferences Data, thus, getting back a string and then gets the address of of that string (i.e. gets back the same thing as Data).
In other words this code:
Surname(&*Data);
does exactly the same as this code:
Surname(Data);
So, now let's take a look at Surname:
int Surname(string *MyData)
{
for (int i=0; i<10 ; i++)
{
NumLast++;
string *Temp = new string[NumLast+1]; // temporary array
for (int jjj=0; jjj<NumLast; jjj++)
Temp[jjj]=MyData[jjj];
delete[] MyData;
MyData=Temp;
MyData[NumLast]="John";
}
return 0;
}
This weird function accepts a pointer to a string and loops 10 times doing stuff. Let's see what happens in the first iteration of the loop...
First, it increments NumLast (which goes from -1 to 0). Then it allocate an array of strings, of length NumLast + 1 (i.e. of length 1). So far so good.
Now you might think the function would enter the for loop. But it won't: remember that at that point NumLast and jjj are both 0 and therefore, jjj < NumLast is false.
The code will then delete[] MyData (that is, it will delete whatever MyData points to), set MyData to point to the temporary array allocated earlier in the loop, and then set the first element (at index 0) to the string "John".
In the second iteration of the loop, the function again increments NumLast (which will now be 1). It will again allocate an array of strings, this time of length 2.
The loop will be entered this time. It will copy the first entry from MyData into the first entry from Temp. And it will exit.
Again, MyData will be deleted, and the pointer will be made to point to the newly allocated array.
Rinse. Lather. Repeat.
Finally, the function will exit. We go back to main, which will now execute this bit of code:
for (int iii=0; iii<10; iii++)
cout << Data[iii] << endl;
Wait a second though. Where does Data point to? Well... it points to data that has already been deleted long ago. Why?
Well, Surname received a copy of the Data pointer. When it called delete[] MyData it deleted the array that it MyData pointed to (which was the same array that Data pointed to). When Surname later did MyData=Temp all that changed was MyData (the copy of the pointer local to the function Surname) and Data (the pointer in main) was unaffected and continued to point to the now deleted memory.
Others have explained how you can get the effect you want and I won't repeat what they wrote. But I would urge you to sit down and think about what Surname does and how the code is unclear and confusing and how it can be rewritten so that it's easier to understand and less prone to error.
For those who in the future will need the solution to the same problem here is the amended code:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int NumLast=-1;
int Surname(string *&MyData)
{
for (int i=0; i<10 ; i++)
{
NumLast++;
string *Temp = new string[NumLast+1];
for (int jjj=0; jjj<NumLast; jjj++)
Temp[jjj]=MyData[jjj];
delete[] MyData;
MyData=Temp;
MyData[NumLast]="franci";
}
return 0;
}
void main()
{
string *Data = new string[1]; // inizializza l'array
Surname(Data);
for (int iii=0; iii<10; iii++)
cout << Data[iii] << endl;
system("pause");
}