我是不是用了指针对指针
Am I using pointers to pointers right?
我是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
开始计数。
相关文章:
- 为什么编译器将其解析为函数指针而不是递归调用?
- 指向数组基址的指针而不是指向第一个元素的指针有什么优点?
- 为什么单例使用指针而不是引用?
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 为什么设置/get_default_resource使用指针而不是引用?
- 为什么只有指向函数的指针而不是函数的变量?
- 当 ParamType 既不是指针也不是引用时自动类型推断
- 为什么``polymorphic_allocator`取一个emore _ resource`指针''而不是参考
- 为什么我们使用指针而不是简单地创建特定尺寸的数组
- 为什么它是一个常量指针而不是指向常量指针
- 返回一个原始指针而不是unique_ptr是一种良好的编码实践吗
- 为什么 clang 将字符串文字作为指针而不是数组
- 将指针而不是迭代器传递到std ::复制
- C++为什么atomic_load参数的类型是指针而不是引用?
- 如果我需要多态性,我应该使用原始指针而不是unique_ptr
- G++ 将返回的字符串文本视为常量字符指针而不是常量字符数组
- 在DLL中分配内存并将其指针提供给客户端应用程序,这是不是一种糟糕的做法
- 模板类c中的析构函数:如何删除可能是指针或不是指针的字段?
- 使用指针而不是引用时访问指向结构的指针数组时出现段错误
- 为什么链表使用指针而不是将节点存储在节点内部