简体   繁体   中英

C++ char* error, program crashes

I am trying to write a program that stores char arrays of names.

This is my code

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

char **names;
char *input_name;

int main() {
    names = new char*[10];
    for(int i=0; i<10; i++){
        names = new char[60];
        cout << "Input name" << i << ": \n";
        cin >> input_name;
        strcpy(names[i],input_name);
        cout << names[i] << "\n";
    }
    return 0;
}

Firstly I am getting the cannot convert 'char*' to 'char**' in assignment names = new char[60]; error.

Also, getting the invalid conversion from 'char' to 'const char*' [-fpermissive] strcpy(names[i],input_name); error

I would greatly appreciate it if someone could modify my code and help me out

Thanks

It's names[i] = new char[60]; instead of names = new char[60]; And you forgot to init input_name with input_name = new char[60];

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

char **names;
char *input_name;

int main() {
    names = new char*[10];
    input_name = new char[60];
    for(int i=0; i<10; i++){
        names[i] = new char[60];
        cout << "Input name" << i << ": \n";
        cin >> input_name;
        strcpy(names[i],input_name);
        cout << names[i] << "\n";
    }
    return 0;
}

As you are using c++ you may should consider using std::string instead of char*. As mentioned by PaulMcKenzie in the comments you get into trouble when a name is longer than 59 characters . Plus std::string is more convenient IMO.

The code contains lots of memory leaks! Any data actually new ed should be delete d. Note that the form of delete needs to match the form of new , ie, when an array object was allocated, an array object needs to release using, eg, delete[] names .

When you read into a char array you need to make sure the amount of data in the array isn't exceed, you can limit the number of characters to be read by setting the stream's width, eg:

if (std::cin >> std::setw(60) >> names[i]) {
    // OK - do something with the data
}
else {
    // failed to read characters: do some error handling
}

Of course, in the code snippet you posted you try to reading into input_name which points nowhere: this will result in undefined (probably some crash).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM