Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;什么';s char a[20]={0}和char*a=new char[20]() 我写了一个函数,返回C++中的IP地址,因为我是C++新手,所以我想让我的代码更熟练。我知道创建一个新变量需要new,我们需要删除它_C++ - Fatal编程技术网

C++;什么';s char a[20]={0}和char*a=new char[20]() 我写了一个函数,返回C++中的IP地址,因为我是C++新手,所以我想让我的代码更熟练。我知道创建一个新变量需要new,我们需要删除它

C++;什么';s char a[20]={0}和char*a=new char[20]() 我写了一个函数,返回C++中的IP地址,因为我是C++新手,所以我想让我的代码更熟练。我知道创建一个新变量需要new,我们需要删除它,c++,C++,我不知道为什么char*hostbuffer=newchar[1024]()与char hostbuffer[1024]={0}不同,它们都在创建一个大小为1024的int数组,对吗 std::string ipfunction_Client(){ char *hostbuffer = new char[1024]();---This cannot work //char hostbuffer[1024]={0};---This can work char *IPbuf

我不知道为什么
char*hostbuffer=newchar[1024]()
与char hostbuffer[1024]={0}不同,它们都在创建一个大小为1024的int数组,对吗

std::string ipfunction_Client(){

    char *hostbuffer = new char[1024]();---This cannot work
    //char hostbuffer[1024]={0};---This can work
    char *IPbuffer=new char[1024];
    struct hostent *host_entry;

    gethostname(hostbuffer,sizeof(hostbuffer));

    host_entry=gethostbyname(hostbuffer);

    IPbuffer = inet_ntoa(*((struct in_addr*)host_entry->h_addr_list[0]));-----This is client.cpp 230
    //delete(hostbuffer);
    return std::string(IPbuffer);
}
如果我使用上述代码,valgrind的反馈如下:

Process terminating with default action of signal 11 (SIGSEGV): dumping core
==19697==  Access not within mapped region at address 0x18
==19697==    at 0x406624: ipfunction_Client() (client.cpp:230)
当你使用

char *hostbuffer = new char[1024]();
char hostbuffer[1024]={0};
sizeof(hostbuffer)
的计算结果是指针的大小,而不是数组的大小

当你使用

char *hostbuffer = new char[1024]();
char hostbuffer[1024]={0};
sizeof(hostbuffer)
计算结果为数组的大小

电话

gethostname(hostbuffer,sizeof(hostbuffer));
将根据您使用的声明而不同地工作

这是代码中最重要的区别

如果你使用

const int BUFFER_SIZE = 1024;
char *hostbuffer = new char[BUFFER_SIZE]();

...

gethostname(hostbuffer, BUFFER_SIZE);

您应该看不到行为上的任何差异。

例如,数组是该语言的基本主题,因此不是教科书的替代品。对常量使用所有大写标识符成为了一个非常坏的习惯。@Slava,被指控有罪。它实际上咬了我一口,来自其他人代码的枚举和来自第三方C库的宏,捕获它并不愉快,尽管它会产生编译错误。如果不会的话——上帝保佑他抓到了这个bug。谢谢,这些真的帮助了我。名称冲突至少不会编译,有了这些讨厌的标识符,它真的很有可能会编译。那将是一场灾难。