0

I'm trying to run a dynamic array that employs strings, but when I push it through a function I get compile errors 'dynamicArray': undeclared identifier, 'string':undeclared identifier, and illegal use of type 'void'. All of these errors point to the header for some reason.

I call the pointer here:

string* dynamicArray = NULL;

I call the function here:

populateArray(dynamicArray);

What is in the header:

void populateArray(string *&dynamicArray);

The function:

void populateArray(string *&dynamicArray)
{
char decide;
bool moreStrings = true;
int counter = 0;
while (moreStrings == true)
{
    counter ++;
    dynamicArray = new string[counter];
    cout << "\nEnter your string here:";
    cin >> dynamicArray[counter - 1];
    cout << "\nDo you want to enter another string? Y/N:";
    cin >> decide;
    decide = toupper(decide);
    if (decide == 'N')
    {
        moreStrings = false;
    }
}
}

PS: vector may be better, but I'm afraid that isn't an option. Please only offer fixes that deal with pointers.

Mark Bell
  • 28,985
  • 26
  • 118
  • 145
user2954467
  • 93
  • 1
  • 1
  • 4

3 Answers3

0

You need to include <string> in your header file.

BTW, there might be potential memory leak in your code, if moreString is true, dynamicArray will point to another new string array, without deleting current one.

jeffw
  • 11
  • 2
0

With #include <string> and using namespace std; added, it compiles just fine for me.

#include <string>
#include <iostream>
using namespace std;

void populateArray(string *&dynamicArray);

int main(){
    string* dynamicArray = NULL;
    populateArray(dynamicArray);
    return 0;
}

void populateArray(string *&dynamicArray)
{
    char decide;
    bool moreStrings = true;
    int counter = 0;
    while (moreStrings == true)
    {
        counter ++;
        dynamicArray = new string[counter];
        cout << "\nEnter your string here:";
        cin >> dynamicArray[counter - 1];
        cout << "\nDo you want to enter another string? Y/N:";
        cin >> decide;
        decide = toupper(decide);
        if (decide == 'N')
        {
            moreStrings = false;
        }
    }
}
dwschrute
  • 94
  • 1
  • 11
0

I see a bigger problem than the missing include and the using clause...

You wrote:

dynamicArray = new string[counter];

But this will allocate a new memory area for you every time. It does not copy the previously allocated elements. IF you don't want to use std::vector, you need to use malloc for the first element and than call realloc to copy your previously allocated data to your new one.

Check this form more info: What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?

Community
  • 1
  • 1
nmenezes
  • 910
  • 6
  • 12