Home > C/C++, Programming > Pointer

Pointer

Spending weekend with Pointer.

1. Increment

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

int main() 
{ 
 int *ptr = NULL ; 
 int i; 

 int my_array[] = { 1,2,3,4}; 
 ptr = my_array; 

 for(int i=0; i < 4; i++) 
 { 
   cout << "Address : " <<  ( ptr + i)  << " Value : " <<  *(ptr + i)  << "\n" ; 
 }  
 return 0; 
}

2. Copy String

#include <stdio.h>
char *my_strcpy(char *dst, char const *src)
{
  char *p;
  p = dst;

  while( *src != ''  )
  {
    *p++ = *src++ ;
  }

 *p = '';
 return dst;

}

int main()
{
  char strDst[80];
  char strSrc[80] = "this is string";

  my_strcpy(strDst, strSrc);
  puts(strDst);
}

3. Struct

#include <stdio.h>

struct tag {
  char first_name[30];
  char last_name[30];
  int age ;
};

char *my_strcpy(char *dst, char const *src)
{
  char *p;
  p = dst;

  while( *src != ''  )
  {
    *p++ = *src++ ;
  }

 *p = '';
 return dst;

}

void print_employee(struct tag *a)
{

  printf("-----------------------------------\n");
  printf("First Name: %s \n",  a->first_name);
  printf("Last Name: %s \n",   a->last_name);
  printf("Age: %d \n",   a->age); 
  printf("-----------------------------------\n");

}

struct tag employee;

int main()
{

  struct tag *ptr_employee;
  ptr_employee = &employee;

  my_strcpy(employee.first_name, "Tonny");
  my_strcpy(employee.last_name, "Kusdarwanto");
  ptr_employee->age = 27;   

  print_employee(ptr_employee) ; 

}

2. Dynamic Array 1D

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

int *ptr;

int main()
{
 ptr = (int *)malloc(SIZE*sizeof(int)) ;
 if(ptr == NULL)
 {
   printf("Error! \n");
   return (-1);
 }

 for(int i=0; i< SIZE ; i++) 
 {
   ptr[i] = 2;
 }

 for(int i=0; i< SIZE ; i++) 
 {
   printf("%d \n", *(ptr + i) );
 }

 return 0;
}

2. Dynamic Array 2D

#include <stdio.h>
#include <stdlib.h>

#define COLS 10

typedef int RowArray[COLS];

RowArray *ptr_array;

int main(void)
{
 int nRow = 10;
 ptr_array =  (RowArray *)  malloc( nRow * COLS * sizeof(int) );

 if (ptr_array == NULL)
 {
  printf("Error");
  return (-1);
 }

 for(int i=0;i<nRow;i++)
 {
  for(int j=0;j<COLS;j++)
  {
   ptr_array[i][j] = i*j ;
  }
 }

 for(int i=0;i<nRow;i++)
 {
  for(int j=0;j<COLS;j++)
  {
   printf("%2d ", ptr_array[i][j]) ;
  }
  printf("\n");
 }
 return 0;
}

 

Reference:

Advertisements
Categories: C/C++, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: