Skip to content

An Issue about char* or char** #3765

Closed
Closed
@Mr-JingShi

Description

@Mr-JingShi

char *p = (char *) &cmd[count]; \

I am confused about &cmd[count],then I test

https://www.onlinegdb.com/

include <iostream>
#include <typeinfo>

int main()
{
    const char *cmd[128] = {0};
    
    std::cout << typeid(&cmd[0]).name() << std::endl;
    std::cout << std::is_same<decltype(&cmd[0]), const char**>::value << std::endl;
    
    {
        std::cout << "--test 1--" << std::endl;
        char *p = (char *) &cmd[0];
        if (asprintf(&p, "bit_rate=%d", 100) == -1) {
            std::cout << "error" << std::endl;
        }
        std:: cout << "p:" << (p ? p : "null") << std::endl;
        std:: cout << "cmd[0]:" << (cmd[0] ? cmd[0] : "null") << std::endl;
        free(p);
    }
    
    {
        std::cout << "--test 2--" << std::endl;
        char *p = 0;
        if (asprintf(&p, "bit_rate=%d", 100) == -1) {
            std::cout << "error" << std::endl;
        }
        std:: cout << "p:" << (p ? p : "null") << std::endl;
        std:: cout << "cmd[0]:" << (cmd[0] ? cmd[0] : "null") << std::endl;
        free(p);
    }
    
    {
        std::cout << "--test 3--" << std::endl;
        char *p = (char *) cmd[0];
        if (asprintf(&p, "bit_rate=%d", 100) == -1) {
            std::cout << "error" << std::endl;
        }
        std:: cout << "p:" << (p ? p : "null") << std::endl;
        std:: cout << "cmd[0]:" << (cmd[0] ? cmd[0] : "null") << std::endl;
        free(p);
    }
    
    {
        std::cout << "--test 4--" << std::endl;
        char **p = (char **) &cmd[0];
        if (asprintf(p, "bit_rate=%d", 100) == -1) {
            std::cout << "error" << std::endl;
        }
        std:: cout << "*p:" << (*p ? *p : "null") << std::endl;
        std:: cout << "cmd[0]:" << (cmd[0] ? cmd[0] : "null") << std::endl;
        free(*p);
    }

    return 0;
}
PKc
1
--test 1--
p:bit_rate=100
cmd[0]:null
--test 2--
p:bit_rate=100
cmd[0]:null
--test 3--
p:bit_rate=100
cmd[0]:null
--test 4--
*p:bit_rate=100
cmd[0]:bit_rate=100

We can use test 2、4 case, why test 1 case?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions