Sending an array of pointers as an argument to another function - c++

I'm writing a game script, sort of in vein of 80's Rouge. My problem is that I want to send a pointer, *p_pixel_grid[8192], to another function without changing it. The other function has to recall the grid via this pointer, it supposed to have access to that part of the memory. It is necessary to redraw the grid at a later stage. Im unable to find a way, or syntax, to send it further. Any suggestions?
char grid_pointer(char grid[8192]) *//this function is just a test function to check if I can send it a pointer as an argument*
{
for (int i=0; i<=8191; i++)
{
cout << grid[8192];
cout << "a";
}
}
void lvl_loader ()
{
FILE* plik;
switch(menu())
{
case 1:
{
plik = fopen("lvl 1.txt", "r");
break;
}
case 2:
{
plik = fopen("lvl 2.txt", "r");
break;
}
case 3:
{
plik = fopen("lvl 3.txt", "r");
break;
}
}
char pixel_grid[32][128];
for (int i=0; i<=31; i++)
{
for (int j=0; j<=127; j++)
{
pixel_grid[i][j] = fgetc(plik);
//cout << pixel_grid[i][j];
}
}fclose(plik);
char *p_pixel_grid[8192]; int pointer_counter=1;
for (int i=0; i<=31; i++)
{
for (int j=0; j<=127; j++)
{
p_pixel_grid[pointer_counter]=&pixel_grid[i][j];
cout << *p_pixel_grid[pointer_counter];
pointer_counter++;
}
}
grid_pointer(&*p_pixel_grid[8192]); //here, I want send this pointer to another function, possibly unchanged. The other function has to use that pointer to recall to data loaded from the .txt
}

void grid_pointer(char ptr[][128])
{
std::cout << ptr[0][1];
std::cout << ptr[10][10];
}
int main()
{
char pixel_grid[32][128];
pixel_grid[0][1] = 'a';
pixel_grid[10][10] = 'b';
grid_pointer(pixel_grid);
}

I'm not sure how true this declaration
is here char *p_pixel_grid[8192]; because arrays are implicitly converted to pointers to their first element.
That is, it is better to make char p_pixel_grid[8192];
Passing a pointer to the array char grid_pointer(char grid[8192]) to the function; Also performed a little incorrectly. The required syntax looks like this:
void grid_pointer(char ptr[][128])
And instead of passing two parameters to the function - the pointer and the size. It is advisable to use span, it describes an object that can refer to a continuous sequence of objects with the first element of the sequence in the zero position.
#include <span>
#include <iostream>
void grid_pointer(std::span<char> grid)
{
std::cout << grid.data() << std::endl;
}
int main()
{
char p_pixel_grid[8192];
p_pixel_grid[0] = 'a';
p_pixel_grid[1] = 'b';
grid_pointer(std::span{ p_pixel_grid });
}
DEMO

Related

'char' array issue, custom print function and strcpy_s problem

I just started C++ and now I'm making a simple program. But don't know how to fix this problem.
I'm not a native english speaker so some sentences may not be understandable.
int main()
{
char test[5][4] = { "abc", "def", "ghi", "jkl", "mno" };
for (int i = 0; i < 5; ++i)
std::cout << test[i] << "\t";
return 0;
}
with this simple code, I made a print function
void printTest(char* pArr)
{
for (int i = 0; i < 5; ++i)
std::cout << pArr[i] << "\t";
}
Then in my main function, I typed printTest(*test);
but the result was 'a b c d'
while my expectation was 'abc def ghi jkl mno'
So I fixed printTest function like below
(changed const char* test[5][4] = { ... }
in main function)
void printTest(const char** pArr)
{
for (int i = 0; i < 5; ++i)
std::cout << pArr[i] << "\t";
}
which worked well.
The problem is, I want to use strcpy_s fucntion also.
strcpy_s(test[0], "xyx"); like this.
As strcpy_s get char* for the first parameter (not const char*),
I think I need to use char* for my array, and print function.
While that thing cause a wrong printing issue.
Did i wrote something wrong in my printTest function?
Or Is there any way that I can use strcpy_s function with const char* parameter?
PS. I used std::string and made it as I expected.
But I want to have a understanding and control of Char array.
I don't think void printTest(const char** pArr) will work with
char test[5][4].
The c++ compiler should refuse something like
void printTest(const char** pArr);
char test[5][4];
printTest(test);
Because test is a pointer to char [4],
while printTest() expects a pointer to char *.
You may have interesting in this function:
void printTest2(const char (*pArr)[4] )
{
for (int i = 0; i < 5; ++i)
std::cout << pArr[i] << "\t";
std::cout << "\n";
}
And the const keyword tells compiler (and what more important, the reader of your code) that "you won't modify the contents of 'pArr'". So compiler will not allow you to strcpy to pArr[i]. And this will compile and run.
void printTest3(char (*pArr)[4] )
{
for (int i = 0; i < 5; ++i)
{
strcpy(pArr[i], "123");
std::cout << pArr[i] << "\t";
}
std::cout << "\n";
}
...
printTest3(test);
I think you are a but confused about he use of const. Don't worry, it's happened to pretty much every one.
What's important to understand is that a non-const variable can be implicitly cast to a const variable at any time, but the reverse is not possible.
For your function PrintTest()
// Here, the const char** declaration is correct, your function only prints pArr,
// and the caller should not expect the function to modify his precious data.
// Another thing to remember: pArr is valid (and thus constant) only within
// the scope of PrintTest(). It simply does not exist anywhere else.
void printTest(const char** pArr)
{
for (int i = 0; i < 5; ++i)
std::cout << pArr[i] << "\t";
}
// this naturally allows printing of const and non-const data, as one would expects.
const char const_strings[2][4] = { "abc", "def" };
printTest(const_strings); // works!
// Note that if printTest() required a non_const pointer, the line above
// would not compile.
// const_strings being const, there is no way to modify it using strcpy_s();
// The code below also works fine,
char modifiable_strings[2][4] = { "tuv", "xyz" };
printTest(modifiable_strings); // works!
strcpy_s(modifiable_strings[0], "abc"); // is OK, because modifiable is not const.
printTest(modifiable_strings); // works, with different output!

how to pass and retrieve char array in c++

I am trying to pass a character array to a function. Set the values onto a character array. Then retrieve it and print using another function. But not able to get the result. Here is the code
class cSummary{
private:
char *cSummaryTable[2];
public:
void printSummary();
void setSummary(char *ptr, int stage);
char *getSummary();
};
void cSummary::printSummary(){
char *cPtr = getSummary();
for(int i = 0; i < 2; i++){
cout << cPtr[i] << endl;
}
}
void cSummary::setSummary(char ptr[], int stage){
switch(stage){
case 0:
cSummaryTable[0] = ptr;
break;
case 1:
cSummaryTable[1] = ptr;
break;
}
}
char *cSummary::getSummary(){
return *cSummaryTable;
}
int main(int argc, char const *argv[])
{
cSummary summary;
summary.setSummary("first message!", 0);
summary.setSummary("second message!!", 1);
summary.printSummary();
return 0;
}
getSummary is the problem since it only returns the first string. Notice the assymmetry between getSummary and setSummary, setSummary has a stage parameter but there's no such parameter in getSummary. That should have been a clue that something was wrong. I would recode like this
char *cSummary::getSummary(int stage) {
return cSummaryTable[stage];
}
void cSummary::printSummary() {
for(int i = 0; i < 2; i++){
cout << getSummary(i) << endl;
}
}
And I'll add the obiligatory piece of good advice. You should learn to program modern C++, which doesn't use arrays and pointers, but uses the much safer and easier to understand std::string and std::vector instead.

Pointer being freed was not allocated even though it was allocated before

I have error that says error for object 0x7ffbaf002000: pointer being freed was not allocated. But I have printed out the memory address and it was indeed allocated before at 0x7ffbaf002000 in the function allocFlights(Flight**, int) inside the loop when flight[0] = (Flight*) malloc(sizeof(Flight) * 60). So I print out the memory address at std::cout << flight[0] << std::endl in function deAllocFlights(Flight**, int) to see if it's there and it is there at 0x7ffbaf002000 inside the loop
I don't understand why I have this problem. I'm still new at C++.
Here is the struct Flight:
typedef struct {
int flightNum;
char origin[20];
char destination[20];
Plane *plane;
}Flight;
void getAllFlights(Flight **flight) {
FILE *file = fopen("reservation.txt", "r");
int i = 0, totalFlights;
if(file == NULL)
{
perror("Error in opening file");
}
fscanf(file, "%d\n", &totalFlights);
*flight = (Flight*) malloc(sizeof(Flight*) * totalFlights);
allocFlights(flight, totalFlights); // Allocate here
.
.
.
deAllocFlights(flight, totalFlights); // Error: Deallocate here
fclose(file);
}
Function allocFlights
void allocFlights(Flight **flight, int totalFlights) {
for (int i = 0; i < totalFlights; i++) {
flight[i] = (Flight*) malloc(sizeof(Flight) * 60);
std::cout << flight[i] << " " << i << std::endl; // Print out memory address
}
}
Function deallocFlights
void deAllocFlights(Flight** flight, int totalFlights) {
for (int i = 0; i < totalFlights; i++) {
std::cout << flight[i] << " " << i << std::endl; // Print out memory address
free (flight[i]);
}
}
Main:
int main() {
Flight *flight;
getAllFlights(&flight);
free(flight);
return 0;
}
You're deallocating your first flight twice. So the second time you deallocate it, the system tells you that it hasn't been allocated because, although it was allocated, it was also deallocated. You don't need to call free(flight); at the end because you already deallocated all flights in deAllocAllFlights(). As mentioned by David Schwartz in the comments, this is because flight[0] is the same as *flight (or as he put it *(flight + 0)).
There is missing one star everywhere.
The code works with the original variable as array of pointers to Flight (or pointer to pointers to Flight). Therefore it has to be defined with double star:
int main() {
Flight **flight;
getAllFlights(&flight);
free(flight);
return 0;
}
And the same for every function:
void getAllFlights(Flight ***flight) {
...
*flight = (Flight**) malloc(sizeof(Flight*) * totalFlights);
void allocFlights(Flight ***flight, int totalFlights) {
for (int i = 0; i < totalFlights; i++) {
// dereference the pointer first and then access array:
(*flight)[i] = (Flight*) malloc(sizeof(Flight));
void deAllocFlights(Flight*** flight, int totalFlights) {
for (int i = 0; i < totalFlights; i++) {
std::cout << (*flight)[i] << " " << i << std::endl; // Print out memory address
// dereference the pointer first and then access array
free ((*flight)[i]);
The original code accessed directly the pointer to the variable defined in main function and used it as an array which meant it went to the address behind the variable for index 1 and even more with higher indices.
Also note, that flights is much better name for the variable and all the other parameters as it's actually array. That would make the code more clear and potentially give better chance to avoid mistakes like this.

Find char* element in array of char* in C++

I'm trying to write function that search for char * element in array of char* and the function start check this element, if the element exist in the array I will have "found", if not it should be "inserted" and the element added to the array.
I wrote this code but I cannot know how to try it, the program always gives me exception, what can I do to check the element in my pointer array?
void checkFunction(char*myArray[], char *element,bool flag)
{
for (int i = 0; i < strlen(*myArray) ; ++i)
{
if (myArray[i] == element)
{
flag = true;
}
}
*myArray = element;
flag = false;
if (flag)
{
cout << "Found" << endl;
}
else
{
cout << "Inserted" << endl;
}
}
C++ Way
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
vector<string> myStrings { "One", "Two", "Three" };
// std::find() finds the first element that matches a value
auto it = find(begin(myStrings), end(myStrings), "Twooo");
if (it != end(myStrings)) {
cout << "We found this string; do something..." << endl;
}
}
Few remarks regarding your function:
1.Why do you need the third parameter bool flag, instead of having it as local variable?
2.If you want to expand an array you should copy the old to a newly allocated and then add the new element, you can not just do: *myArray = element;
3.If you want to iterate through the array length/ size, instead of:
for (int i = 0; i < strlen(*myArray) ; ++i)
pass an additional parameter to your function, that indicates the number of elements in the array.
With std::string and std::vector you could do something like:
void check_insert (std::vector<std::string>& v, std::string& c) {
for (auto i = 0; i < v.size(); ++i) {
if (v[i] == c) {
std::cout << "Found!\n";
return;
}
}
v.push_back(c);
std::cout << "Inserted!\n";
}

Sending an array between two functions C++

I am trying to send a array of 15 integers between two functions in C++. The first enables the user to enter taxi IDs and the second functions allows the user to delete taxi IDs from the array. However I am having an issue sending the array between the functions.
void startShift ()
{
int array [15]; //array of 15 declared
for (int i = 0; i < 15; i++)
{
cout << "Please enter the taxis ID: ";
cin >> array[i]; //user enters taxi IDs
if (array[i] == 0)
break;
}
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "\n";
if (goBack == 0)
update();
}
void endShift ()
{
//need the array to be sent to here
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "\n";
if (goBack == 0)
update();
}
Any help is great valued. Many thanks.
Since the array has been created on the stack, you would just need to pass the pointer to the first element, as an int*
void endshift(int* arr)
{
int val = arr[1];
printf("val is %d", val);
}
int main(void)
{
int array[15];
array[1] = 5;
endshift(array);
}
Since the array is created on the stack, it will no longer exist once the routine in which it was created has exited.
Declare the array outside of those functions and pass it to them by reference.
void startShift(int (&shifts)[15]) {
// ...
}
void endShift(int (&shifts)[15]) {
// ...
}
int main() {
int array[15];
startShift(array);
endShift(array);
}
This isn't exactly pretty syntax or all that common. A much more likely way to write this is to pass a pointer to the array and its length.
void startShift(int* shifts, size_t len) {
// work with the pointer
}
int main() {
int array[15];
startShift(array, 15);
}
Idiomatic C++ would be different altogether and use iterators to abstract away from the container, but I suppose that is out of scope here. The example anyway:
template<typename Iterator>
void startShift(Iterator begin, Iterator end) {
// work with the iterators
}
int main() {
int array[15];
startShift(array, array + 15);
}
You also wouldn't use a raw array, but std::array.
It won't work to use a local array in the startShift() function. You are best off to do one or more of the following:
Use an array in the function calling startShift() and endShift() and pass the array to these functions, e.g.:
void startShift(int* array) { ... }
void endShift(int* array) { ... }
int main() {
int arrray[15];
// ...
startShift(array);
// ...
endShift(array);
// ...
}
Don't use built-in arrays in the first place: use std::vector<int> instead: that class automatically maintains the current size of the array. You can also return it from a function altough you are probably still best off to pass the objects to the function.
void endShift (int* arr)
{
arr[0] = 5;
}