简体   繁体   中英

how to use char ** properly?

I have two examples, which of these two is better and why? In both cases, I got the same result. I have chosen container simply to hold strings.

Example 1:

    char *c_ptr[] = {};
    int num;
    if (fill_array(c_ptr, &num) != 0) {
          cout << "Error" << endl;
    }
    for (int i = 0; i < num; i++) {
       cout << "Str[" << i << "] = " << c_ptr[i] << endl;
    } 
    // free pointer..

    // Function implementation 
    int fill_array(char *c_ptr[], int *count) {
        vector<string> v = {"haha", "hehe", "omg", "happy, learning!"};
        *count = v.size();
        int i = 0;

        for (vector<string>::iterator it = v.begin(); it != v.end(); it++, i++) {
            c_ptr[i] = (char*)malloc((*it).size() + 1);
            strncpy(c_ptr[i], (*it).c_str(),(*it).size() + 1);
        }
        return 0;
    }


Example 2:

    char **c_ptr = NULL;
    int num;
    if (fill_array(&c_ptr, &num) != 0) {
          cout << "Error" << endl;
    }
    for (int i = 0; i < num; i++) {
       cout << "Str[" << i << "] = " << c_ptr[i] << endl;
    } 
    // free double pointer..

    // Function implementation 
    int fill_array(char ***c_ptr, int *num) {
        vector<string> v = {"haha", "hehe", "omg", "happy, learning!"};
        *num = v.size();
        int i = 0;

        *c_ptr = (char **)malloc(*num * sizeof(char *));
        for (vector<string>::iterator it = v.begin(); it != v.end(); it++, i++) {
            c_ptr[i] = (char*)malloc((*it).size() + 1);
            strncpy(*c_ptr[i], (*it).c_str(),(*it).size() + 1);
        }
        return 0;
    }

Result :

Str[0] = haha
Str[1] = hehe
Str[2] = omg
Str[3] = happy, learning!

Also What is the use of empty bracket in array? Is it good programming habit vs dynamic allocation?

** is pointer to a pointer or simply we can say it a double pointer.

Double pointers are better to use when we are passing a pointer variable from main() or simply a function to another function.

By looking at your code, I would like to suggest you one thing and that is, avoid using global variables.

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