0

gals and everything in between, first off, I want to say sorry for noob/duplicate question.

TL;DR I want to allocate memory for a 2d array of chars, however I can only do so when the program calls alloc(). Any help is appreciated.

Since you guys love code, here is what I have:

#include <iostream>

using namespace std;
#define LOG(x) cout<<endl<<x<<endl

void alloc(char ***add){

    cout<<"Size: ";int s;cin>>s;
        *add = new char *[s];
        for (int i = 0; i < s; i++) {
            *(add)[i] = new char[s];
            cout<<add[i][i]<<" ; ";
        }
}

int main() {
    char **c;

    alloc(&c);
    for (int i =0;i<2;i++) {
        for (int j = 0; j < 2; j++) {
            cout<<c[i][j];
        }
        cout<<endl;
    }
    
cin.get();
}

Now whenever I run this code, I get the following error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV).

Also, in the debugger, when the function gets called and I input the size of the array, I get a use of undeclared identifier 'c' error.

Thank you and I apologize again for noob or duplicate question, but I did try the answer I got from Text, alas, to no avail.

  • ***I get a use of undeclared identifier 'c' error*** That would prevent you from getting an executable so you could not debug anything. – drescherjm Oct 12 '20 at 15:28
  • Ty for your input @drescherjm , but as I said, im a noob. Why it works and I am able to click the debug icon is beyond me at this point. – Stefan Campan Oct 12 '20 at 15:35
  • 1
    What ever source you use for learning c++ you really should choose something else. The shown code is far from what you would do in c++. The way `alloc` is implemented prevents you from properly releasing the allocated memory and doing boundary tests. – t.niese Oct 12 '20 at 17:35
  • @t.niese and I don't suppose you could recommend something else? I learned what I know mostly from the internet and stackoverflow. – Stefan Campan Oct 13 '20 at 06:04
  • There is [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) here on StackOverflow. StackOverflow is a Q&A platform for specific questions but not a good starting point to learn a language. You should first learn the basics and concepts of a language, and that is done by using a good book. – t.niese Oct 13 '20 at 11:52

1 Answers1

0

*(add)[i] does not look quite right, it indexes the add variable and dereferences the pointer afterwards. Those parentheses have no effect.

Try the opposite order, i.e. (*add)[i]

Sven Nilsson
  • 1,861
  • 10
  • 11