C++

char* str 与 char str[]

2018-03-07  本文已影响1人  Kai_Z

char* str = "HelloWorld"

例程

#include <iostream>

void printhello(void)
{
    char *ptr1 = "HelloWorld";
    std::cout << "ptr1 address: "<< (void*)ptr1 << std::endl;
}

void printword(void)
{
    char *ptr2 = "HelloWorld";
    std::cout << "ptr2 address: "<< (void*)ptr2 << std::endl;
}

int main()
{
    printhello();
    printword();
    char *str1 = "HelloWorld";
    char *str2 = "HelloWorld";
    std::cout << "str1 address: " << (void*)str1 << std::endl;
    std::cout << "str2 address: " << (void*)str2 << std::endl;
    std::cout << "str1 " << ((str1 == str2) ? "equal to " : "unequal to ")
        << "str2" << std::endl;
    return 0;
}
//本人电脑的输出
ptr1 address: 00953138
ptr2 address: 00953138
str1 address: 00953138
str2 address: 00953138
str1 equal to str2

通过上面的例程,可以看出ptr1,ptr2,str1,str2全部指向同一块内存空间

char str[] = "HelloWorld"

例程

#include <iostream>

int main()
{
    char str1[] = "HelloWorld";
    char str2[] = "HelloWorld";
    std::cout << "str1 "<< ((str1 == str2) ? "equal to " : "unequal to ")
        <<"str2"<< std::endl;
    std::cout << "str1 address: "<< (void*)str1 << std::endl;
    std::cout << "str2 address: "<< (void*)str2 << std::endl;
    str1[0] = 'h';
    std::cout << str1 << std::endl;
    return 0;
}
//输出结果
str1 unequal to str2
str1 address: 00F3FE6C
str2 address: 00F3FE78
helloWorld

通过上面例程可以看出str1与str2指向不同的内存地址,且可以随意更改str1所指向的内存里的内容(str2也是一样)。

void foo(char* p) 与 void foo(char p[])形参

例程

#include <iostream>
void foo(char* p)
{
    p[0] = 'h';
    std::cout << p << std::endl;
    std::cout << (void*)p << std::endl;
}

void foo2(char p[])
{
    p[0] = 'w';
    std::cout << p << std::endl;
    std::cout << (void*)p << std::endl;
}

int main()
{
    //foo("HelloWorld"); //调用函数会产生错误
    //foo2("HelloWorld");
    char str[] = "HelloWorld";
    foo(str);
    foo2(str);
    system("pause");
    return 0;
}
//输出的结果
helloWorld
00D3FD9C
welloWorld
00D3FD9C
上一篇下一篇

猜你喜欢

热点阅读