C ++ char得到错误?

时间:2015-01-10 19:18:02

标签: c++ arrays char pointers

#include <iostream>

int main()
{
    char[] name = { "Nitish prajapati" }; 
    char* namePointer = &name ;

    std::cout << "\n name    = " << name;
    std::cout << "\n &name    = " << &name;
    std::cout << "\n &namePointer    = " << &namePointer;
    std::cout << "\n namePointer    = " << namePointer;

    return 0;
}

为什么这个程序会出错:expected unqualified-id before '[' token?         和  解释你如何实际使用char以及引用和解除引用(即指针)

2 个答案:

答案 0 :(得分:3)

这两个陈述都是错误的

char[] name = { "Nitish prajapati" }; 
char* namePointer = &name ;

在C ++中,数组的有效声明类似于

char name[] = { "Nitish prajapati" }; 

至于第二个语句,则没有从类型char ( * )[17]char *的隐式转换。 声明的初始化器具有类型char ( * )[17],而声明的指针具有类型char *

你应该写

char* namePointer = name ;

char ( *namePointer)[17] = &name ;

答案 1 :(得分:0)

应该是:

const char name[] = {"Nitish prajapati"}; 
const char* namePointer = name ;