我是不是用了指针对指针

Am I using pointers to pointers right?

本文关键字:指针 是不是      更新时间:2023-10-16

我是c++编程的新手,试图通过阅读Alex Allain写的一本名为跳到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;
}

billz所说的和**x必须更改为x[i][j]。由于您似乎是新手,因此最好将乘法表作为单独的块(在两个for循环之外)打印。

此处:

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++)

循环是远的,如果你做了正确的下一个bot会导致一个问题,因为你索引超出了数组的末尾。幸运的是(这里有一个bug)。这些行应该是:

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.

注意://注意,因为你的第一个bugX [i]将从数组的末尾移1。

分配数组时:

 x = new int[size];

可以访问以下元素:X [0] => X [size-1]

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