Reputation: 23
The objective of this program is of right now to set each array variable of the 2D array,
char mass_data_shift[9][9]; equal to 'T' . Which should equal 100 Ts overall.
This is done by calling a void function with this 2D array address as an argument. Calling it by a pointer to then be initialized in a loop.
Inside the loop is were the 2D array should be set to T.
*mass_data[mass_data_counter][mass_data_counter_two] = 'T';
However..... the program results in:
Meaning the program, somewhere, is writing out of bounds. Any help would be appreciated in both making the program run without a segmentation fault and/or fixing other mistakes.
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
void mass_data_define(char (*mass_data)[9][9]){
int mass_data_counter;
int mass_data_counter_two = 0;
for (mass_data_counter=0;mass_data_counter<9;mass_data_counter++){
do {
std::cout << "|Array #1 " << mass_data_counter
<< " ::: |Array #2 " << mass_data_counter_two
<< std::endl;
*mass_data[mass_data_counter][mass_data_counter_two] = 'T';
std::cout << *mass_data[mass_data_counter][mass_data_counter_two];
mass_data_counter_two++;
std::cout << "---------End of Counter 2 Init Code----------" << std::endl;
} while (mass_data_counter_two < 9);
mass_data_counter_two = 0;
}
}
int main()
{
char mass_data_shift[9][9];
mass_data_define(&mass_data_shift);
std::cout << "-END-" << std::endl;
return 0;
}
Final Edit: The main cause was solved by szym below. Sorry about the whitespaces and missing iostream , was a formatting issue when I made the post. Also changed the loop to fit the array length as suggested below.
Upvotes: 2
Views: 108
Reputation: 1927
Short Answer: Here's a one-line fix to your code so may continue to use a pointer and still not get a segmentation fault:
(*mass_data)[mass_data_counter][mass_data_counter_two] = 'T';
Long Answer: Read Create a pointer to two-dimensional array.
For an in-depth understanding of how to pointers to access multi-dimensional arrays, read this.
Upvotes: 0
Reputation: 5846
*mass_data[mass_data_counter][mass_data_counter_two] = 'T';
Should be
(*mass_data)[mass_data_counter][mass_data_counter_two] = 'T';
Naturally, same goes for the line:
std::cout << *mass_data[mass_data_counter][mass_data_counter_two]
But really this pointer type is not necessary to pass array by reference in C/C++.
You should instead declare:
void mass_data_define(char mass_data[9][9]) {
// To read:
char z = mass_data[3][6];
// To write:
mass_data[2][1] = 'C';
}
// elsewhere
char my_mass_data[9][9];
mass_data_define(my_mass_data);
Upvotes: 1