0

I have to make a vector that stores char pointers. Each pointer should only point to a single char like 'a' or 'b'. I don't get any compile errors, but when I run my program, it crashes. I cannot use std::string or any of its functions, they have to just be characters.

std::vector<char*> myVector;
myVector.reserve(10);
myVector.at(0) = new char['a'];

Why does the program crash? Shouldn't I be able to create new char pointers in memory as I go?

The_Redhawk
  • 214
  • 1
  • 2
  • 11

2 Answers2

3

You should use push_back method of vector instead of using at when you have not pushed anything inside vector. Also, you should use new char('a') instead of using bracket, which has other meaning. Look at this minimal code that works just fine:

#include <iostream>
#include <vector>

int main()
{
    std::vector<char*> myVector;
    myVector.push_back(new char('a'));
    std::cout << *myVector[0] << std::endl;
}
Ho1
  • 1,239
  • 1
  • 11
  • 29
1

Let's see line by line:

std::vector<char*> myVector;

Is there a need to keep a vector of char pointers?
What's following tells us you only want to store 1 char in there, so just use std::string, it'll be way easier.

myVector.reserve(10);

The reserve() methods are only used for pre-allocation, they don't actually change the size of your vector, only its capacity. For every vector: 0 <= size <= capacity. std::vector::at() will simply throw if you try to access something outside [0;size[

myVector.at(0) = new char['a'];

As we said, the .at(0) call will throw an exception here. But something funny will happen on the right side. Since allocating a new array is usually done with new T[N] where T is the type of the elements and N the size of the array, this will implicitly convert the char 'a' into an int (which is 97) and therefore allocate an array of 97 uninitialized elements.

m88
  • 1,968
  • 6
  • 14
  • So I adjusted to this ``` myVector.reserve(10); myVector.push_back(new char('a')); ``` The error is now gone and I can print 'a' to the screen using std::cout << *myVector.at(0); Without the * to dereference the vector element, it prints jibberish to my screen. This means that I am dealing with a pointer to a char correct? – The_Redhawk Feb 25 '21 at 19:44
  • `myVector.at(0)` is a pointer to a char, correct. – m88 Feb 25 '21 at 20:09