在C/C++中,以下两行代码有什么区别:
char *str1="hello";
char *str2={"hello"};
char *str1="hello";
char *str2={"hello"};
这种情况下仅使用样式。它们都会导致相同的结果,并且它们都是不良形式。您应该使用const char *str1 =“hello”;
。
请查看https://dev59.com/LnA75IYBdhLWcg3wH1RB#3462768。
这些大括号是多余的。
使用“gcc -S”生成以下代码的汇编形式可以确认它们生成完全相同的内容(每种情况下常量略有不同):
#include <iostream>
using namespace std;
void test1() {
const char *str1="hello1";
cout << str1 << endl;
}
void test2() {
const char *str2={"hello2"};
cout << str2 << endl;
}
int main() {
test1();
test2();
}
数组和“字符串”之间没有区别,因为字符串是字符数组。