user4167396
user4167396

Reputation: 29

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

Upvotes: 1

Views: 1882

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153975

The code contains lots of memory leaks! Any data actually newed should be deleted. Note that the form of delete needs to match the form of new, i.e., when an array object was allocated, an array object needs to release using, e.g., 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, e.g.:

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).

Upvotes: 0

H4kor
H4kor

Reputation: 1562

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.

Upvotes: 2

Related Questions