Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I'm doing a BubbleShot project and I hae to create a 15*18 table to sort my bubbles, I have to use pointers but I'm not goot to this, I try to initialise it but I have a buffer overflow that I can solve, here is my .h

C++
#pragma once
class CPlateau
{
public:
	CPlateau();
	~CPlateau();
	int **table;
	void Init();
};


and here is my .cpp
C++
#include "pch.h"
#include "CPlateau.h"
CPlateau::CPlateau()
{
	table = new int* [18];
	for (int i = 0; i < 18; i++)
	{
		table[i] = new int[15];
	}
	
	for (int i = 0; i < 15; i++)
		{
			table[i][17] = 10 + i % 2;
		}
}
CPlateau::~CPlateau()
{
	for (int i = 0; i < 15; i++)
		delete[] table[i];
	delete[] table;
}
void CPlateau::Init()
{
	for (int i = 0; i < 17; i++)
		for (int j = 0; j < 9; j++)
			table[i][j] = rand() % 6 + 1;


}


What I have tried:

I tried to use malloc and calloc but it get worst and I don't know what to change
Posted
Updated 21-Jan-21 22:11pm
v2

1 solution

Look at your code:
C++
table = new int* [18];
for (int i = 0; i < 18; i++)
{
	table[i] = new int[15];
}

for (int i = 0; i < 15; i++)
	{
		table[i][17] = 10 + i % 2;
	}
Look at it closely, and see what you are doing:
C++
table = new int* [18];
You create an array of 18 pointers to integers: that's one dimension.
C++
for (int i = 0; i < 18; i++)
{
	table[i] = new int[15];
}
You fill in each pointer with an array of 15 integers.
C++
for (int i = 0; i < 15; i++)
	{
		table[i][17] = 10 + i % 2;
	}
You go through the first 15 elements of the outer array, trying to set element 17 of the inner array (which contains 15 elements) to a value ...

If you want to create a 18 * 15 jagged array and fill it, use a nested loop:
C++
int** table = new int*[18];
int x = 0;
for (int i = 0; i < 18; i++)
    {
    table[i] = new int[15];
    for (int j = 0; j < 15; j++)
        {
        table [i][j] = x++;
        }
    }
 
Share this answer
 
Comments
CPallini 22-Jan-21 4:11am    
5.
Axel Patron 22-Jan-21 4:25am    
Thank you so much, I'm really not confortable with pointers ^^
OriginalGriff 22-Jan-21 5:30am    
If you are going to play with C or C++, get comfortable with them - you will be using them a lot, and a lack of understanding here will both cause you a lot of grief and waste a lot of your time!
Axel Patron 22-Jan-21 5:47am    
Do you know good website to learn it? I'm kinda lost cause I'm starting to learn it and this code is a project for my school
OriginalGriff 22-Jan-21 6:00am    
Here's a starter:
https://www.codeproject.com/Articles/627/A-Beginner-s-Guide-to-Pointers

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900