注册 登录
编程论坛 C++教室

关于数组和指针的疑问

苍翠的路 发布于 2014-09-16 22:03, 401 次点击
程序代码:

#include<iostream>

using namespace std;

int main()
{
    char *p = "OK";
    cout<< *p <<endl;                //O
    cout<< p <<endl;                //OK

    char ch[] = "OK";
    cout << *ch << endl;             //O
    cout << ch << endl;             //OK
   
    int q[] = {1,2,3};
    cout << *q << endl;              //1
    cout << q << endl;              //0012ff34(地址值)

        return 0;


为什么输出p、ch、q的结果是这样?
*p、*ch、*q的作用都是对首地址取引用?
还有,数组名到底是不是指针?
还请大家指教。
6 回复
#2
stop12042014-09-16 23:10
指针 指向 数组的首个地址.

数组名也是指向数组的首个地址
#3
fl89622014-09-19 07:41
cout<< *p <<endl;                //O  p 指向首地址, *p解引用,输出第一个字母
    cout<< p <<endl;                //OK

    char ch[] = "OK";
    cout << *ch << endl;             //O  同上
    cout << ch << endl;             //OK
   
    int q[] = {1,2,3};
    cout << *q << endl;              //1 同上
    cout<<q<<endl:  //输出首地址。
#4
fl89622014-09-19 07:47
回复 楼主 苍翠的路
char *p = "OK"; 加一个 const char*p="ok"
#5
绝处逢生_6152014-09-21 13:12
#include<iostream>
#include<string>
using namespace std;

int main()
{
    char *p = "OK";
    cout<< *p <<endl;                //O
    cout<< p <<endl;                //OK

    char ch[] = "OK";
    cout << *ch << endl;             //O
    cout << ch << endl;             //OK
   
    int q[] = {1,2,3};
    cout << *q << endl;              //1

    for(int i=0;i<3;++i)
    cout << q[i] << endl;              //0012ff34(地址值)

        return 0;
}

看懂指针就知道为什么了
#6
zcdjt2014-09-21 16:38
*p输出的是首个字母,p输出的是首个地址。
#7
七夜之华2014-09-21 17:04
数组名不是指针,还有你说的第二条都是按首地址开始输出数组内的数据元素
1