码迷,mamicode.com
首页 > 编程语言 > 详细

C++数组和指针

时间:2014-08-22 17:54:29      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:style   os   io   数据   ar   代码   amp   linux   size   

先看下面一段代码:

#include <iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main() {
	int time[] = {1,2,3};
	int *q ;
	q = time;
	cout<<*q<<" "<<q<<endl;
	char arr[]="hello world";
	string *p;
	string str[] = {"linux","unix"};
	p = str;
	cout<<*p<<" "<<p<<endl;
	char* pc;
	pc = arr;
	cout<<arr<<" "<<*pc<<endl;
	cout<<pc<<endl;
	string s = "linux";
	string *ps;
	ps = &s;
	cout<<ps<<*ps<<endl;

	return 0;
}


 

下面是运行结果:

1 0x7fff6de21a20
linux 0x7fff6de21a00
hello world h
hello world
0x7fff6de219f0 linux
解释:

一直以来都对指针有点疑惑.所以没事的时候就专门写了这段代码,代码不难.却对我认识指针和数据有非常大的帮助.

例子中的time,str和s的所有的输出,根据书中的描写,就很容易判断出来输出的数据.唯一让我困惑的就是char*和char[].

在c和c++中如果直接赋值char* p="hello world",是相当于char arr[]="hello world"; p = arr的.在这里如果不特别声明"hello world"为string,则认为是字符数组的.

p指向数组的首地址.输出*p,是输出第一个字符.如果输出p,则输出整串字符.这是我认识的char*和非char指针的区别.





C++数组和指针

标签:style   os   io   数据   ar   代码   amp   linux   size   

原文地址:http://blog.csdn.net/xglhw1987/article/details/38758623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!