gpt4 book ai didi

c++ - C++ 和 C 中指针和数组的区别

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:53 26 4
gpt4 key购买 nike

我知道 C++ 是与 C 完全不同的语言。但 C++ 充当 C 的超集。

我不知道为什么这段代码在 C 中编译和运行时只有几个警告并抛出类似 scalar object 'a' requires one element in initializer 的错误

这里是:

#include<stdio.h>
int tabulate(char **head){
//Stuffs here
}

int main(){
char **a={"Abc","Def"};
tabulate(a);
return 0;
}

关于指针和数组,C++ 是否为 C 代码带来了其他差异?

最佳答案

const char ** 没有声明指向数组的指针,而是声明指向指向 const char 值的指针的指针。只是类型 const char*[] 在传递时衰减为 const char** ,例如,作为函数参数。所以 a 是一个标量对象,而 {"abc","def"} 是一个数组初始化器;因此错误消息scalar object 'a' requires one element in initializer

因此,使用数组语法,它适用于 c++ 和 c:

#include<stdio.h>
int tabulate(const char **head){
//Stuffs here
return 0;
}

int main(){
const char *a[]={"Abc","Def"};
tabulate(a);
return 0;
}

关于c++ - C++ 和 C 中指针和数组的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43585731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com