2011/12/20

[C/C++]Pointer to Array or Array of Pointer

[Pointer to array]
Example: int *ptr1[10];
這代表有一個array, 它用來存10個int pointer 的資料
The ptr1 is an array of 10 pointer to integers.
[Array of pointer]
Example: int (*ptr2)[10];
這代表有一個ptr2 指到存有10個integer 的陣列
The ptr2 is a pointer to array of 10 integers.

[Example for Array of pointer]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h> //isspace
#include <string.h>
#define YEARS 2
#define Act 3
void initial_array(double (*pt)[Act],int);
void copy_ptr(double (*source)[Act],double (*target)[Act],int);
int main(int argc, char *argv[])
{
    double Two_array[YEARS][Act];
    double (*target)[Act];

    printf("Please input value:\n");
    initial_array(Two_array,YEARS);
    target = new double[YEARS][Act]; // Assign Memory
    copy_ptr(Two_array,target,YEARS);
    printf("Copy result is:\n");
    for(int i=0;i<YEARS;i++)
       for(int j=0;j<Act;j++)
         printf("%.2lf ",target[i][j]);
        
    system("pause");
    return 0;  
}
void initial_array(double (*pt)[Act],int m)
{
     for(int i=0;i<m;i++)
         for(int j=0;j<Act;j++)
            scanf("%lf",&pt[i][j]);
}
void copy_ptr(double (*source)[Act],double (*target)[Act],int m)
{
     double (*ptr)[Act];
     ptr = source;
     for(int i=0;i<m;i++){
        for(int j=0;j<Act;j++)
         target[i][j]=*(*(ptr+i)+j);
     }
     printf("Pointer Tag and Pointer increment:\n");
}

沒有留言: