天天看點

C++數組和指針

先看以下一段代碼:

#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的全部的輸出,依據書中的描寫,就非常easy推斷出來輸出的資料.唯一讓我困惑的就是char*和char[].

在c和c++中假設直接指派char* p="hello world",是相當于char arr[]="hello world"; p = arr的,"hello world"是在内在的文字常量區,是以直接輸出p的結果是hello world

繼續閱讀