-1

我是 C++ 编程的新手,并试图通过阅读 Alex Alllain 的一本名为 Jumping into C++的电子书来学习这门语言,我目前已经完成了动态内存分配一章,我必须说我发现指针很难理解。

本章的最后是一系列我可以尝试的练习题,我已经完成了第一个问题(花了我一段时间才让我的代码工作),即编写一个构建任意维度乘法表的函数(你必须使用指针来解决问题),但我对我的解决方案不满意,如果它是正确的,如果我以正确的方式使用指针,我希望有经验的人指出缺陷,如果有,下面是我的自己解决问题的方法:

// pointerName.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <string>

void multTable(int size){

    int ** x, result;
    x = new int*[size]; //  lets declare a pointer that will point to another pointer :).
    result = 0; 

    for(int h = 0; h < size; h++){ // lets store the address of an array of integers.
            x[h] = new int [size];      
    }
    std::cout << std::endl << "*********************************" << std::endl; // lets seperate. 
    for(int i=0; i < size+1; i++){ // lets use the pointer like a two-dimensional array.
        for(int j=0; j < size+1; j++){
            result = i*j; // lets multiply the variables initialized from the for loop.
            **x = result; // lets inialize the table.
            std::cout << **x << "\t"; // dereference it and print out the whole table.
        }
        std::cout  << std::endl;
    }
    /************* DEALLOCATE THE MEMORY SPACE ************/
    for(int index = 0; index < size; index++){
        delete [] x[index]; // free each row first.  
    }
    delete [] x; // free the pointer itself.
}

int main(int argc, char* argv[]){

    int num;
    std::cout << "Please Enter a valid number: ";
    std::cin >> num; // Lets prompt the user for a number.
    multTable(num);

    return 0;
}
4

2 回答 2

2

billz 所说的以及 **x 必须更改为 x[i][j]。由于您看起来很新,因此将乘法表打印为一个单独的块(在两个 for 循环之外)是一个好习惯。

于 2013-01-08T00:42:08.043 回答
1

这里:

for(int i=0; i < size+1; i++){ // lets use the pointer like a two-dimensional array.
    for(int j=0; j < size+1; j++)

如果你正确地完成了下一个机器人,那么循环会很远,因为你的索引超出了数组的末尾。对你来说幸运(有以下错误)。这些行应该是:

for(int i=0; i < size; i++){ // lets use the pointer like a two-dimensional array.
    for(int j=0; j < size; j++)

这一行:

 **x = result; // lets inialize the table.

你可能的意思是:

x[i][j] = result; // lets inialize the table.

注意: // 注意,因为您的第一个错误 x[i] 会超出数组末尾一个。

分配数组时:

 x = new int[size];

您可以访问元素: x[0] => x[size-1]

这是因为有size元素,但您从 开始计数0

于 2013-01-08T00:55:09.767 回答