cont 와 pointer

전전컴/C++ 2013. 10. 22. 23:08
# of 1
  
#include <iostream>
using namespace std;

void main(){
	
	int a = 6;

	int *const p = &a; //반드시선언때초기화해줘야한다.
	*p = 12;  //포인터변수의주소값이변하지않는다.
	//++p; p의주소값을변경하려는행위이기때문에에러가발생한다.

	const int *q = &a;
	//*q=20;  q가가리키는곳의값을변경할수가없게된다.
}
# of 2
  
#include <iostream>
using namespace std;


int main(){
	int *p = new int[10];
	
	for(int i = 0 ; i<10 ; i++){
		*(p+i)=i+1;//p[i] = i +1;
		
		cout<< *(p+i) << endl;
	}


	delete[] p;
	p = NULL;
	if(p!=NULL){
		delete[] p;
	}
}
# of 3 함수 호출은 하나의 output만 return 가능하다. multi output을 하고 싶다면, call by reference를 고려해야한다. -


-
  
#include <iostream>
using namespace std;

void swap( int* a , int *b){
	cout<<"void swap( int* a , int *b) 호출"<<endl;
	int temp;
	temp = *a;
	*a=*b;
	*b= temp;
}

void swap( int& a, int& b){
	cout<<"void swap( int& a, int& b) 호출"<<endl;
	int temp;
	temp = a;
	a= b;
	b= temp;
}

void main(){
	int a = 5, b = 9;
	swap( &a  , &b ) ;
	cout<< a <<' ' << b << endl;
	swap( a  , b ) ;
	cout<< a <<' ' << b << endl;
}

# of 4 -


-
  
#include <iostream>
using namespace std;

int findmax(int *t, int size);
void main(){
	int a[2][3]={{1, 2, 3}, {4, 5, 6}};

	int sum=0;
	int column[3]={0};
	for(int i = 0 ; i <2 ; i++){
		for(int j=0; j <3; j++){
			sum += a[i][j];
			column[j]+=a[i][j];
			
		}
		cout<<i<<"행의합"<< sum <<endl;
		sum=0;
	}
	cout<<endl;
	for(int i=0;i<3;i++){
		cout<<i<<"열의합";
		cout<<column[i]<<endl;
	}
	//	sum=0;
	//for(int j=0 ; j<3; j++){
	//	for(int i=0; i < 2 ; i++){
	//		sum+=a[i][j];
	//	}
	//	cout<<j<<"열의합"<< sum <<endl;
	//	sum=0;
	//}
	


	cout << endl;
	int b[5]= { 13,9,5,20,2};
	cout << "최대값"<< findmax( b, 5) << endl;
}

int findmax(int *t, int size){
	int temp=0;
	int i;
	temp=*t;
	for ( i = 0 ; i<size ; i ++){
		if( *(t+i) > temp )  temp = *(t+i);
	}

	return temp;
}

설정

트랙백

댓글

아래의 코드는 hi라는 string를 가리키고 있는 포인터 p를 changeAddress로 넘긴다. 그러나 changeAddress로 받을 때, char* q라는 포인터를 만들고 여기에다가 포인터p가 가진 hi의 시작 주소값을 저장한다. 그러므로 q의 주소를 암만 바꿔봤자, main함수의 포인터p에 저장된 주소값은 바뀌질 않는 병크가 터진다. 다르게 응용하면 자료구조에서 어떤 자료를 찾기위해서 주소값을 리턴받는다고 가정하자. 함수는 하나의 값만 리턴받을수 있으므로, 주소값을 리턴 받아서 해야지 하는 생각은 ㅄ짓이다. 여러개의 값을 리턴받기 위해선 call-by-reference가 꼭 필요하다. 지금 아래의 코드는 call-by-value로써 복사한후에 처리를 하기때문에 input인자로 output을 받을순없다.
  
#include <iostream>
#include <string>
using namespace std;
char* ch = "hello";
void changeAddress(char *q ){
	q = new char[strlen(ch)+1];
	strcpy(q,ch);

}

void main(){
	char *p = "hi";
	changeAddress(p);

	cout<<p<<endl;
//출력결과--- hi
}
아래는 함수호출시 포인터를 넘기고, 넘긴 포인터의 주소를 변경하기위해서 이중포인터를 사용하였다.

이중포인터이기에 *q를 이용하면 p에 저장된 주소를 바꿀수 있고

**q를 하면 hi에 접근할수 있다.

#include <iostream>
#include <string>
using namespace std;
char* ch = "hello";
void changeAddress(char **q ){
	*q = new char[strlen(ch)+1];
	strcpy(*q,ch);

}

void main(){
	char *p = "hi";
	changeAddress(&p);

	cout<<p<<endl;
//출력결과 hello
}

 이 방법 말고도 같은 메모리 주소에 또 다른 이름을 붙일수 있는 reference를 이용해도 된다.

개인적으로 이방법이 젤 깔끔하고 쉬운것 같다.



#include <iostream>
#include <string>
using namespace std;
char* ch = "hello";
void changeAddress(char *(&q) ){
	q = new char[strlen(ch)+1];
	strcpy(q,ch);

}

void main(){
	char *p = "hi";
	changeAddress(p);

	cout<<p<<endl;
	int i =5;
	int *b=&i;
	int **a=&b;
	a=&b;
//출력결과 hello
}
이 코드들은 함수 호출시 동적배열을 하는데, 메모리 해제를 하지 않아 메모리 누수가 발생하므로 그리 좋은 예제는 아님을 밝혀둔다.

설정

트랙백

댓글

C++ 2주차

전전컴/C++ 2013. 10. 22. 22:13


-----------------------------code----------------------------------

#include <iostream> #include <string> using namespace std; int sum(const int* a, int b){ int i, s=0; for(i=0; i<b; i++){ s=s+ *a++; } return s; } void increment(int *a, int b){ int i; for(i=0; i <b; i++){ *a++ +=1; //*a++ === *(a++); !====(*a)++; 주의할점 } } void test2(int **a){ cout<<"hello"<<sizeof(*a)<<endl; } void main(){ int a[5]={1,2,3,4,5}; cout<<"SUM"<< sum(a,sizeof(a)/sizeof(int)) <<endl; increment(a,5); cout<<"a배열의값들:"<<endl; for(int i=0 ; i<5; i++){ cout<<a[i]<<endl; } cout<<"sizeof(a)의값은int형4byte에5개요소가있으므로"<< sizeof(a)<<endl; }


설정

트랙백

댓글

포인터를 이용한 함수의 호출



----------------------------code--------------------------------------------------

#include <iostream> using namespace std; int compare(void* item1, void* item2){ if( *(int*)item1>= *(int*)item2){ return 1; }else return 0; } void* larger(void* item1, void* item2, int (*compare)(void* , void*) ){ if( (*compare)(item1, item2) >0 ){ return item1; }else{ return item2; } } void main(){ int a= 6; int b=7; cout<< *(int*)larger(&a, &b, compare)<<endl; }


설정

트랙백

댓글

General Linear List

전전컴/C++ 2013. 10. 16. 22:38





---------------------------------code-------------------------------------------
 
#include <iostream>
using namespace std;

typedef struct tListNode{
	int data;
	struct tListNode *link;
}ListNode;

typedef struct{
	int count;
	ListNode* head;
	ListNode* pos;
}List;


List* createList(){
	List* p = (List*)malloc(sizeof(List));
	p->count = 0;
	p->head = NULL;
	return p;
}

void destroyList(List* p){
	ListNode *pDel=NULL, *pNext=NULL;
	
	if(p->count<=0){
		free(p);
		return;
	}

	for(pDel=p->head; pDel!=NULL; pDel = pNext){
		pNext = pDel->link;
		free(pDel);
		cout<<"del"<<endl;
	}
	free(p);
}

bool searchList(List* p, ListNode** pPre, ListNode** pLoc, int item){
	for( (*pPre)=NULL, (*pLoc)=p->head ; (*pLoc)!=NULL; ){
		if( (*pLoc)->data == item){
			return true;
		}else if( (*pLoc)->data > item ){
			break;
		}
			(*pPre)=(*pLoc);
			(*pLoc)=(*pLoc)->link;
	}
		
	
		return false;
}

void insertList(List* p, ListNode* pPre, int item){
	ListNode *q = (ListNode*)malloc(sizeof(ListNode));
	q->link = NULL;
	if(pPre == NULL){
		p->head = q;
		q->data = item;
	}else{
		q->link = pPre->link;
		pPre->link = q;
		q->data = item;
	}

	p->count++;
}

void addNodeList(List* p, int item){
	ListNode *pPre = NULL, *pLoc = NULL;

	bool found = searchList(p, &pPre, &pLoc, item);

	if(!found){
		insertList(p, pPre, item);
	}
}
void deleteList(List* p, ListNode *pPre, ListNode *pLoc){
	if(pPre == NULL){
		p->head = pLoc->link;
	}else{
		pPre->link = pLoc->link;
	}
	
	free(pLoc);
	p->count--;
}

void removeList(List* p,  int item){
	ListNode *pPre, *pLoc;
	bool found = searchList(p, &pPre, &pLoc, item);

	if(found){
		deleteList(p,pPre,pLoc);
	}
}

void display(ListNode *head){
	ListNode *p;
	if(head ==NULL) return;
	p=head;
	do{
		cout<<p->data<<endl;
		p=p->link;
	}while(p!=NULL);
}

bool traverseList(List* p, int fromWhere, int* data){
	if( p->pos == NULL || fromWhere ==0 ){
		p->pos=p->head;
	}else{
		p->pos = p->pos->link;
	}

	if(p->pos != NULL){
		*data = p->pos->data;
		return true;
	}else{
		*data = 0;
		return false;
	}
	

}

void main(){
	List *p = createList();
	addNodeList(p, 10);
	addNodeList(p, 20);
	addNodeList(p, 30);

	bool check = false;
	int n=0;
	int data;
	
	cout<<"traverseList 함수를이용한display부분"<<endl;
	do{
		check = traverseList(p,n++,&data);
		if(check) cout<<data<<endl;
	}while(check);


	removeList(p,20);
	cout<<"display함수를이용한display 부분"<<endl;
	display(p->head );
	destroyList(p);
}


설정

트랙백

댓글