2012-01-25 95 views
0

我一直在做一些練習從一本書,我想知道如果你能告訴我,如果他們是正確的。這不是功課,我只是在練習。我評論了我應該做的,我的實際代碼C++練習定義類型

#include <iostream> 
#include <string> 
using namespace std; 

//int main(){} 

// 1 
char *ptc;        //pointer to char 
int Array[10];       //array of 10 ints 
int (&arrayRef)[10] = Array;   //ref to Array 
string *pts;       //pointer to a array of strings 
char** pptc;       //pointer to pointer to char 
const int const_int =0;     //constant integer 
const int* cpti;      //constant pointer to a integer 
int const* ptci;      //pointer to constant integer 

// 3 
typedef unsigned char u_char;   //u_char = 2; 
typedef const unsigned char c_u_char; //c_u_char = 2; 
typedef int* pti;      //pti = &Array[0]; 
typedef char** tppc;     //ttpc = ptc; ? 
typedef char *ptaoc;     //pointer to array of char 
typedef int* pta;      //array of 7 pointers to int ? 
pta myPTA = (int *)calloc(7, sizeof(int)); 
typedef int** pta2;      //pointer to an array of 7 pointers to int ? 
pta2 mypta2 = &myPTA; 
/* ??? */        //array of 8 arrays of 7 pointers to int 

// 4 
void swap1(int *p, int *q)    //this should swap the values of p & q but the last line isn't working q = &aux?? 
{ 
    int aux;       //int a = 5, b = 8; 
             //swap1(&a, &b); 
    aux = *p; 
    *p = *q;       //it returns 8 and 8 
    q = &aux; 
} 

int main() 
{ 
} 

編輯: 的問題是:我如何申報的7個8個指針數組的數組爲int

這是正確的?

typedef char** tppc;     //ttpc = ptc; ? 
typedef char *ptaoc;     //pointer to array of char 
typedef int* pta;      //array of 7 pointers to int ? 
pta myPTA = (int *)calloc(7, sizeof(int)); 
typedef int** pta2;      //pointer to an array of 7 pointers to int ? 
pta2 mypta2 = &myPTA; 

爲什麼不是功能swap1的工作?

+0

最好與你所面臨的一個實際問題(回覆:downvotes發生),以另一種方式 – phwd

回答

1

廣告1)

要聲明的7個指針的8個陣列的DECLARE陣列爲int你必須鍵入以下內容:

int* arr[8][7]; 

廣告2)

你的交換函數不工作,因爲您正在設置指向函數局部變量的指針。

一個小的變化,一切都應該很好地工作:

void swap1(int *p, int *q)    //this should swap the values of p & q but the last line isn't working q = &aux?? 
{ 
    int aux;       //int a = 5, b = 8; 
             //swap1(&a, &b); 
    aux = *p; 
    *p = *q;       //it returns 8 and 8 
    *q = aux; // <-- notice change here! 
} 
+0

@DrewDormann:這是一個很好的辦法讓你的籌碼損壞。我從我自己痛苦的經歷中知道;) – Constantinius

+0

@DrewDormann:你是對的,對我很恥辱...... – Constantinius

+0

我沒有打折過,我忽略了一些東西...... :) –