0

I'm dealing with dynamic arrays in C++. Help with the following code.

I'm trying to read the characters one by one and make the C-string. If the array size is not enough, I increase it. But the function increaseArray works with an error and returns a string with other characters. What I am wrong?

void increaseArray(char* str, int &size){
    char* newStr = new char[size * 2];
    for (int i = 0; i < size; i++){
        newStr[i] = str[i];
    }
    size *= 2;
    delete[] str;
    str = newStr;
}

char* getline()
{
    int size = 8;
    char* str = new char[size];
    char c;
    int index = 0;
    while (c = getchar()) {
        if (index == size) increaseArray(str, size);
        if (c == '\n') {
            str[index] = '\0';
            break;
        };
        str[index] = c;
        index++;
    }
    return str;
}
Zven
  • 3
  • 1
  • 1
    This " str = newStr;" sets the local variable str to newStr. That local variable is immediately discarded. You want a pointer-to-pointer or a reference. –  Jan 21 '17 at 14:48
  • 1
    Why don't you use `std::string` or even `std::vector` ?? – Walter Jan 21 '17 at 15:27
  • 1
    _"I'm trying to read the characters one by one and make the C-string. If the array size is not enough, I increase it"_ Literally what `std::string` is for. Why don't you use it and save yourself the trouble? Your code would not pass review in my team. – Lightness Races in Orbit Jan 21 '17 at 15:31

2 Answers2

2

In function increaseArray you are assigning newStr to str however str is local copy of pointer in increaseArray function thus change is not visible outside it.

Simplest fix is to change increaseArray signature to:

void increaseArray(char*& str, int &size)

So reference to pointer will be passed, thus changes to str inside increaseArray will be visible outside it.

Marcin Sucharski
  • 1,191
  • 9
  • 9
1

You could do that. Its simple..

#include <string.h>
#include <stdlib.h>
using namespace std;
void increaseArray(char* &str, int size){
     str = (char *)realloc(str,size*2);
}
Leandro
  • 114
  • 2
  • 10
  • Unfortunately, it doesn't help much as you ignored the pointer returned by `realloc`. – ForceBru Jan 21 '17 at 15:04
  • @ForceBru I forgot that. I already made the necessary changes to that. – Leandro Jan 21 '17 at 15:15
  • Actually, since the OP used `new[]` to allocate his memory, he cannot use `realloc` according to [this answer](http://stackoverflow.com/a/33706568/4717805) – cmourglia Jan 22 '17 at 10:07