How to initialize pointer to pointer with premade data? - c++

I have a pointer to a pointer, since I can't pass dynamic arrays to functions. However, if I want to initialize that pointer-to-pointer with premade data, how can I set it since {a,b,c} notation for arrays won't work for pointers?

You can do this:
static int row1[] = {1, 2, 3};
static int row2[] = {4, 5, 6, 7};
static int row3[] = {8, 9, 10, 11, 12, 13};
static int *pptr[] = {row1, row2, row3};
At this point, pptr can be assigned to an int**:
int **p = pptr;

[This answer is only relevant if you need a double*. Your question was edited to say pointer to pointer - if that's what you need, this answer is not relevant.]
You can do this instead:
double fValues[3] = { 1, 2, 3 };
The variable fValues is already a pointer - array variables without the [] are pointers to the first element of the array. This is not a dynamic array, so you don't need to allocate/free its memory.
Assuming your function that takes a double pointer looks something like this:
void Func(double* pDbl) {...}
you'd call it like this:
Func(fValues);

You can create small dynamic arrays recursively something like this:
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct
{
int* pValues;
size_t Count;
} List;
const List ListEnd = { NULL, 0 };
List NewList(int Value, List SubList)
{
List l;
l.Count = SubList.Count + 1;
if (SubList.Count == 0)
{
l.pValues = malloc(sizeof(int));
}
else
{
l.pValues = realloc(SubList.pValues, l.Count * sizeof(int));
}
if (l.pValues == NULL)
{
// do proper error handling here
abort();
}
// moving data isn't necessary if the list elements are
// in the reverse order
memmove(&l.pValues[1], &l.pValues[0], SubList.Count * sizeof(int));
l.pValues[0] = Value;
return l;
}
void PrintDynArr(int* pValues, size_t Count)
{
while (Count--)
{
printf("%d\n", *pValues++);
}
}
int main(void)
{
int* p;
PrintDynArr(p = NewList(1,
NewList(2,
NewList(3,
NewList(4, ListEnd)))).pValues,
4);
free(p);
return 0;
}
Output:
1
2
3
4

Related

Get array index from pointer difference in c or c++

I know how to get a pointer from a pointer and adding a index. But is it possible to get the index of a array if you only have a pointer to the array beginning and a pointer to one element element?
#include <iostream>
#include <array>
auto pointer_from_diff(auto *x, auto *y) -> auto {
return // ? what here?
}
auto main() -> int {
auto x = std::array{1, 2, 3, 4};
auto *p = &x[2];
std::cout << pointer_from_diff(x.data(), p) << std::endl;
}
Because someone seem to not like the question being tagged in c, here is some actual c-code for those of you who does not speek c++.
#include <stdio.h>
int pointer_from_diff(int *x, int *y) {
return ?;// ? what here?
}
int main() {
int x[] = {1, 2, 3, 4};
int *p = &x[2];
int index = pointer_from_diff(x, p);
printf("%d", pointer_from_diff(x, p));
}
Note: I marked this as c++/c, not because I want to use c, but because my guess is that the solution is similar for both languages. A solution in c that is possible to implement in c++ is therefore acceptable.
I also over/missuse auto for the lols in the c++ version and that is unrelated to the question.
&x[k] is the same as &x[0] + k.
Thus, p - &x[0] is &x[0] + 2 - &x[0], which is 2.

How to return a struct which contains an array pointer from a function?

I have this struct and declaration in .h file,
struct strct
{
int *arry;
};
strct func01();
and this function in .cpp file,
strct func01()
{
int temp_arry[] = {5, 6, 7, 8, 9};
strct rtrn;
rtrn.arry = temp_arry;
return rtrn;
}
and i call the function like,
strct test = func01();
printf("%d", test.arry);
It prints some random numbers. I want to print the full array.
Before we start, let's recall the behavior of the sizeof operator:
Case of : int *
int *arry;
int iSize = sizeof (arry); <-- Return size of pointer and NOT number of elements
Case of : int []
int temp_arry[] = {5, 6, 7, 8, 9};
int iSize = sizeof (temp_arry); <-- Return total memory size allocated for 5 elements
You understand now that the composition of your structure does not allow you to determine the number of elements of your int *arry struct member. Therefore, you don't know how many element you should display.
If you wish to keep your program without using the STL: vector, array, ... you must complete your structure as follows:
struct strct
{
int size; // Contains the number of elements to use
int *arry;
};
strct func01();
strct func01()
{
strct rtrn;
int tab_size = 5;
// it is a temp variable. Destroyed when function ends.You can not use it !
int temp_arry[] = {5, 6, 7, 8, 9};
// This table is allocated with new and can be used
int *permanent_arry = new int [tab_size];
for (int i=0; i<tab_size; i++)
permanent_arry[i] = i;
rtrn.arry = permanent_arry;
rtrn.size = tab_size;
return rtrn;
}
int main ()
{
strct test = func01();
for (int i=0; i<test.size; i++)
printf("%d ", test.arry[i]);
// dont forget to delete memory
delete [] test.arry;
}
First, this code is wrong because:
the lifetime of temp_arry[] is end after func01 returns.
you are printing a pointer, not an array.
Second, if you want to print the full array, you'd better redesign your code, for example, you may use vector to clean up your code. (this code needs C++ 11)
struct strct
{
std::vector<int> arry;
};
strct func01();
strct func01()
{
std::vector<int> temp_arry = {5, 6, 7, 8, 9};
strct rtrn;
rtrn.arry = temp_arry;
return rtrn;
}
strct test = func01();
for(auto i : test)
std::cout << i << " ";
Note: most of the time there's no point to use built-in arrays as return value, even though it will decay to a pointer prvalue.

c++ int array with values of 2 dimension int array (3d array)

I'm trying to make an array which contain int[][] items
i.e
int version0Indexes[][4] = { {1,2,3,4}, {5,6,7,8} };
int version1Indexes[][4] = { ...... };
int version15Indexes[][4] = { ... };
(total of 16)
int indexes[][][] = { version0Indexes,version1Indexes, .. };
anyone can suggest how to do so ?
Thanks
You can use an array of pointers to array:
int (*indexes[])[4] = { version0Indexes, version1Indexes, .. };
Either you inline your arrays inside indexes:
int indexes[][2][4] = {
{ { 1, 2, 3, 4}, {5, 6, 7, 8} },
{ {....}, {....} }
....
}
Or you make indexes an array of pointers:
int (*indexes[])[4] = { version0Indexes, version1Indexes, .... };
What you wrote in your question is not directly possible because, when used, an array variable is actually a pointer (that's why indices has to be an array of pointers).

How to modify array inside function which doesn't take this array as parameter

What I need is to modify pTab array inside modifyAA(int a) function.
How can I achieve this?
Example Code:
int modifyAA(int a);
int main()
{
*pTab=new int[10]; int a=13;
for(int i=0;i<=9;i++)
pTab[i]=88;
modifyAA(a);
//I'd like to have pTab to be modified after function invoke
return 0;
}
modifyAA(int a){
for(int i=0;i<=9;i++)
pTab[i]=pTab[i]+1;
a=a+pTab[0];
return a;
};
Is it possible to modify array when function doesn't take it as parameter ?
You can use a global variable for the pointer to the first element of the dynamic array:
int * pTab;
int printAA(int a)
{
for (unsigned int i = 0 i != 10; ++i)
{
++pTab[i];
}
return a + pTab[0];
}
int main()
{
pTab = new int[10];
// populate
printAA(13);
}
You could use global variables. This could be practical especially if several functions like printAA() would need to call it.
However there is a risk of using *pTab before it's allocated. And also, you remember now the size, but if later you'd change the size to 10, you would have to find back all the places where you've hardcoded the 10 or the 9.
If the goal of not passing the parameter is mainly because you call the function a lot of times you could opt for a std::bind, creating a kind of dynamic function:
#include <iostream>
#include <functional>
int printDynArr(int* dynarr, size_t sz, int a) // proper function with all parameters
{
for (size_t i = 0; i < sz; i++)
dynarr[i]++; // It's a pointer, so you modify the data where it is stored
a += dynarr[0];
return a;
};
int main()
{
int *pTab = new int[10]; int a = 13; //declaring and alocating - dynamic array
auto printAA = std::bind<int>(printDynArr, pTab, 10, std::placeholders::_1); // dynamic function shortcut with predefind parameters
...
printAA(a); //using function without giving pTab as argument.
std::cin.get();
return 0;
}
If you were to do this "The C++ way", you could use a vector and iterators from stdlib, like so:
#include <vector>
typedef std::vector<int> PTab; // Defines a type for your pTab, it's a vector of integers
int printAA(PTab::iterator from, PTab::iterator until, int a); //declaring some func
int main()
{
PTab pTab(10, 88); // Initializes pTab vector to 10 elements all containing 88
int a = 0;
printAA(pTab.begin(), pTab.begin() + 10, a);
return 0;
}
int printAA(PTab::iterator from, PTab::iterator until, int a)
{
for (PTab::iterator i = from; i != until; ++i)
{
*i++; // Increments current element by 1
}
a += *from; // Adds the value of the from element to a
return a;
};
This way you don't pass the vector itself to the function, instead, you only pass a range of iterators, which gives the function a possibility to access the contents of the vector, but not to modify the vector object itself (ie. clear it, resize it, etc.).

Returning a pointer to an array C++

I have a function that needs to return a pointer to an array:
int * count()
{
static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
return &myInt[10];
}
inside my main function I want to display one of the ints from that array, like here at index 3
int main(int argc, const char * argv[])
{
int myInt2[10] = *count();
std::cout << myInt2[3] << "\n\n";
return 0;
}
this however gives me the error: "Array initializer must be an initializer list"
how do I create an array within my main function that uses the pointer to get the same elements as the array at the pointer?
A few problems in your code:
1) you need to return a pointer to the beginning of the array in count:
return &myInt[0];
or
return myInt; //should suffice.
Then when you initialize myInt2:
int* myInt2 = count();
You can also copy one array into the other:
int myInt2[10];
std::copy(count(), count()+10, myInt2);
Note copying will create a second array using separate memory than the first.
You don't need pointers, references are fine.
int (&count())[10]
{
static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
return myInt;
}
int main(int argc, const char * argv[])
{
int (&myInt2)[10] = count();
std::cout << myInt2[3] << "\n\n";
return 0;
}