简体   繁体   中英

Char matrix in C++?

I have been trying hard with this C++ exercise to no avail.. How do i create a char matrix holding 4 words, with each letter of a word on a char space? This is my attempt.
I want to use null to know where the string ends. And due to the instructions of the excercise i have to use a char matrix. As you can see i tried different aproaches with vector[0] and the rest. Neither of them works.

int ax = 3;
char ** vector = new char* [ax+1];
for (int i = 0; i < ax; i++){
    vector[i] = new char[10];
}
vector[0] = "F","u","t","b","o","l";
vector[1] = "AUTOmata";
vector[2] = "fUT";
vector[3] = "auto";
vector[ax+1] = NULL;

I have been trying hard with this C++ exercise to no avail.. How do i create a char matrix holding 4 words, with each letter of a word on a char space?

No problem. You can use std::vector and std::string for this task. In fact from std::string you can get a C-string (null terminated since you like them) withdata() .

std::vector<std::string> vector {
    "Futbol",
    "AUTOmata",
    "fUT",
    "auto"
};

Live demo


If you want to use C "features" on the other hand:

const int largo = 3;
char** vector = new char* [largo+1];
for (int i = 0; i < largo + 1; ++i)
    vector[i] = new char[10];
strcpy(vector[0], "Futbol");
strcpy(vector[0], "AUTOmata");
strcpy(vector[0], "fUT");
strcpy(vector[0], "auto");

Live demo

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