C ++练习定义类型

时间:2012-01-25 19:32:49

标签: c++ pointers

我一直在做一些书的练习,我想知道你是否可以告诉我他们是否正确。这不是作业,我只是练习。我已经评论了我应该做什么以及我的实际代码

#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()
{
}

编辑: 问题是:我如何声明8个7指针数组的数组到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没有工作?

1 个答案:

答案 0 :(得分:1)

ad 1)

要声明一个包含8个指向int 的8个数组的声明数组,您必须输入以下内容:

int* arr[8][7];

ad 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!
}