Here is my code, and I thought that each cout line will print the respective object the pointer points to. Why is there an error? This prints some random list of numbers, with first always correct.
int* f()
{
int array[10] = {1,2,3,4,5,6,7,8,9,10};
int *p = array;
return p;
}
int main()
{
int* ptr = f();
cout << *(ptr+0) << endl;
cout << *(ptr+1) << endl;
cout << *(ptr+2) << endl;
cout << endl;
}
Your pointer points to array with autamtic storage. The array dies when the function returns and the pointer dangles.
The solution is not using pointer, using vector or dynamic array.
Local arrays are created on the stack, and have automatic storage duration. In your case array is created on the stack and get destroyed when the function f() ends.
there are two ways you can manage so that array remains active through out your program execution.
1) dynamically allocated arrays
//c++
int *array = new int[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
//c++ 11
int *array{ new int[]{ 1, 2, 3, 4, 5 } };
Please always remember to free dynamically allocated array using delete[] if you need to free space.
2) static array
static int array[10] = {1,2,3,4,5,6,7,8,9,10};
Static variables are variables defined using static memory allocation. for more information please see https://en.wikipedia.org/wiki/Static_variable
Related
This is the function:
void print(int arr[], int size)
{
int* count = new int [size];
for(int i = 0; i < size; i++){
count[arr[i]]++;
cout << count[arr[i]] << endl;
}
}
When I call (in my main) print(arr, sizeof(a)/sizeof(a[0])) where a = {4, 2, 4, 5, 2, 3}, I would get the updated count of each number in the array.
Now, let's say I want to do something very similar to this but in my int main():
int* my_arr = new int[10];
my_arr[1]++;
cout << "my_arr[1] = " << my_arr[1];
The last statement prints something like 15799121, which I assume is the memory address of my_arr[1].
How is this not the same in print()? Shouldn't cout << count[arr[i]] << endl; produce the same result?
For default initialization,
otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.
That means given new int [size], the elements of the array are initialized to indeterminate values, use of these values leads to UB, means anything is possible.
You might want value initialization, i.e. new int [size](); all the elements would be initialized to 0 exactly.
I writing a script which receives a structure (Evt) which holds an array of pointers uint16_t *DataChannel[Evt->ChSize[ch]]. I can then loop over the data and print out of the value as so:
for(uint16_t ch=0; ch<sizeof(Evt->DataChannel)/sizeof(Evt->DataChannel[0]); ++ch){
for(int adc_it=0; adc_it<(Evt->ChSize[ch]); ++adc_it){ for(int adc_it=0; adc_it<(Evt->ChSize[ch]); ++adc_it){
std::cout << (Evt->DataChannel)[ch][adc_it] << " ";
}
}
I don't understand where the second bracket comes from ([adc_it]), what it is doing and how it works. I think (Evt->DataChannel) should be a uint16_t which is not an array so why the second bracket?
I tried to replicate this in a quick piece of code:
#include <iostream>
int main()
{
int* test[10];
*(test[0]) = 5;
std::cout << test[0][0] << std::endl; //Gives 5
std::cout << test[0][1] << std::endl; //Seg faults
return 0;
}
Again can some explain what test[0][0] is doing because I have no idea and why it runs but test[0][1] fails?
Cheers
Dom
C++ permits the use of array notation [ ] when dereferencing a pointer.
In the simplest case, you can say something like:
char *ptr = new char[10];
That creates a pointer to char, which points to the first character in an array of ten characters allocated with new[].
After doing this:
char ch = *ptr;
and
char ch = ptr[0];
do the exact same thing. However since there are 10 characters in the array, you can also say:
char ch5 = ptr[5];
to access an element further up the array.
This leads to an eqivalence in C++ (and C, where it originated) that:
ptr[x];
is identical to:
*(ptr + x);
for any pointer / array referenced by ptr and any index x.
Already the first part
int* test[10];
*(test[0]) = 5;
is undefined behaviour, because you dereference an uninitialized pointer value.
Explanation:
int* test[10] is an array of 10 pointers to ints, each pointer
being not initialized and definitely not pointing to a memory that
you reserved to store ints.
test[0] gives an uninitialized pointer; already this statement is
UB
*(test[0]) = 5 dereferences an arbitrary pointer value, definitely
UB
Try:
int* test[10];
int firstLine[5] = { 1,2,3,4,5 };
test[0] = firstLine;
cout << test[0][0]; // gives 1, firstLine[0]
cout << test[0][1]; // gives 2, is the same as firstLine[1]
// cout << test[1][0]; // undefined behaviour, the second pointer in array test is not initialized
I'm working on an assignment involving string pointers. There are two functions. The first takes in an array of strings, places the address of each element into a separate array, and then returns the pointer to that array. The second function takes the pointer that was returned and prints out the elements of the original array with just the pointer. But when I test it, the dereferenced string** ptrToPtr is different in each pointer. I want to know why
Here is Function 1:
string** arrayOfPtrs(string arr[], int size)
{
string* ptrArray; //The array of string pointers
string** ptrToPtr; //A pointer to the array of string pointers
ptrArray = new string[size];
//ptrArray = arr;
int i = 0;
while (i < size)
{
ptrArray = &arr[i];
i++;
ptrArray++;
}
ptrToPtr = &ptrArray;
return ptrToPtr;
}
Here is Function 2:
void outputArray(string** arr, int size)
{
int count = size; //An int variable that stores the size of array
string* ptr = *arr; //A pointer that stores the address to the last element
//in the string pointer array
while (count > 0)
{
cout << *(ptr - count) << " ";
count--;
}
cout << endl;
}
And here is part of main():
string strArr[] = { "echo", "charlie", "delta", "bravo", "delta" };
string** strPtrs;
strPtrs = arrayOfPtrs(strArr, 5);
cout << "Actual results: ";
outputArray(arrayOfPtrs(strArr, 5), 5);
cout << endl << endl;
I'm I going wrong anywhere? Or is there a better way to deference a pointer to a string pointer?
Here is a similar program ran completely in main:
int main()
{
string words[30];
string* s;
s = new string[30];
string** t;
createArray(30, words);
int num = 0;
t = &s;
while (num < 30)
{
s = &words[num];
num++;
s++;
}
string* u = *t;
int j = 30;
for (int i = 0; i < 30; i++)
{
cout << "*(s - " << j << ") - " << *(s - j) << endl;
cout << "words[ " << i << " ] - " << words[i] << endl;
cout << "*(u - " << j << " ) - " << *(u - j) << endl << endl;
j--;
}
}
And this program works perfectly. Any ideas?
This is incorrect:
while (i < size)
{
ptrArray = &arr[i];
i++;
ptrArray++;
}
Replace ptrArray = &arr[i]; with *ptrArray = arr[i];. As it stands now, you're just overwriting the same pointer each time through the loop and never doing anything useful with it.
This is also incorrect:
string* ptrArray; //The array of string pointers
// ...
ptrToPtr = &ptrArray;
return ptrToPtr;
As soon as you return that, it becomes dangling. You're not allowed to use pointers to local (stack) variables once they're out of scope.
Firstly, I see a few problems in your setup
You don't need this for practical reasons. If you want to have the address of each element in the array, you can calculate it by incrementing the pointer to the first element (which is the array in fact). If you only do that for educational reasons forget about this
string* ptrArray = new ... Now you have an array of strings (array is semantically equaivalent to pointer to first element). But you want an array of string pointers. So you need string** ptrArray = new ... and this cascades to the rest of the function being incorrect.
You never delete the array allocated with new. This results in the memory not being free'd. You need to delete[] *strPtrs;in your last code snippet to free the memory you allocated in your method. In general it is a good idea to let the one who allocates the memory be responsibly for freeing it. I show you another idea below to handle this.
After your copy operations the pointer points past your array. Then you return a pointer to it. You applied the correct arithmetics when outputting the values in you second snippet, but I would never want to have such a pointer going around. Conventionally it should point to the first element. At least when deleting the array-pointer it has to point to the first element, otherwise you get undefined behavior e.g. deleting another array.
Lastly:
string* ptrArray; //The array of string pointers
string** ptrToPtr; //A pointer to the array of string pointers
ptrToPtr points to ptrArray, which is a local variable. It becomes invalid when leaving the function and thus it will be undefined behavior to dereference the returned pointer.
There is a common approach used by some standard libraries (e.g. snprintf from cstdio), so the caller is responsible for allocation and deallocation:
void arrayOfPtrs(string arr[], int size,/*new param*/ string** outArray)
{
string** iter = outArray; // Iterator pointer
int i = 0;
while (i < size)
{
*iter = &arr[i];
i++;
iter++;
}
}
What happens here, is that the caller gives the function a pointer to the pointers (it points to the first pointer). Note that a pointer can be used as an array with index operators etc. So it is in fact an array of pointers. You then fill it by incrementing the copied pointer so it jumps from pointer element to pointer element. Where the array actually is stored is not the problem of this function.
Use it like this:
// Variant 1: Use local variable if size is constant
string* arr[5];
arrayOfPtrs(strArr, 5, arr);
std::cout << *arr[0]; // Dereferences a pointer in arr to get the string which is actually in strArr
// Variant 2: Allocate heap memory (if you need dynamic size)
int size ...; // From somewhere
string** arr = new string[size];
arrayOfPtrs(strArr, size, arr);
std::cout << *arr[0]; // Same again
... // Do further work
delete[] arr; // Free memory
So you have to allocate memory (or use a local variable) before you call the function and then pass it to the function. In the double pointer, the first * is meant for the data type which is "pointer to string" and the second designates it as a "pointer-array".
I know that the following is not correct:
int arr[2][3] = {}; //some array initialization here
int** ptr;
ptr = arr;
But I am quite surprised that the following lines actually work
int arr[2][3] = {}; //some array initialization here
auto ptr = arr;
int another_arr[2][3] = {}; //some array initialization here
ptr = another_arr;
Can anyone possibly explain what is the type assigned to ptr in the second block of code, and what happened underneath?
Well, arrays decay to pointers when used practically everywhere. So naturally there's decay going on in your code snippet too.
But it's only the "outer-most" array dimension that decays to a pointer. Since arrays are row-major, you end up with int (*)[3] as the pointer type, which is a pointer to a one-dimensional array, not a two dimensional array. It points to the first "row".
If you want ptr's deduction to be a pointer to the array instead, then use the address-of operator:
auto ptr = &arr;
Now ptr is int(*)[2][3].
In
auto ptr = arr;
arr decays into a pointer to its first element in the normal way; it's equivalent to
auto ptr = &arr[0];
Since arr[0] is an array of three ints, that makes ptr a int (*)[3] - a pointer to int[3].
another_arr decays in exactly the same way, so in
ptr = another_arr;
both sides of the assignment have the type int (*)[3], and you can assign a T* to a T* for any type T.
A pointer to arr itself has type int(*)[2][3].
If you want a pointer to the array rather than a pointer to the array's first element, you need to use &:
auto ptr = &arr;
First, let's look at why you can't assign int arr[2][3] to int **. To make it easier to visualise, we'll initialise your array with a sequence, and consider what it looks like in memory:
int arr[2][3] = {{1,2,3},{4,5,6}};
In memory, the array data is stored as a single block, just like a regular, 1D array:
arr: [ 1, 2, 3, 4, 5, 6 ]
The variable arr contains the address of the start of this block, and from its type (int[2][3]) the compiler knows to interpret an index like arr[1][0] as meaning "take the value that is at position (1*2 + 0) in the array".
However for a pointer-to-pointer (int**), it is expected that the pointer-to-pointer contains either a single memory address or an array of memory addresses, and this/these adress(es) point to (an)other single int value or array of ints. Let's say we copied the array arr into int **ptrptr. In memory, it would look like this:
ptrptr: [0x203F0B20, 0x203F17D4]
0x203F0B20: [ 1, 2, 3 ]
0x203F17D4: [ 4, 5, 6 ]
So in addition to the actual int data, an extra pointer must be stored for each row of the array. Rather than converting the two indexes into a single array lookup, access must be performed by making a first array lookup ("take the second value in ptrptr to get an int*"), then nother array lookup ("take the first value in the array at the address held by the previously obtained int*").
Here's a program that illustrates this:
#include <iostream>
int main()
{
int arr[2][3] = {{1,2,3},{4,5,6}};
std::cout << "Memory addresses for int arr[2][3]:" << std::endl;
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
std::cout << reinterpret_cast<void*>(&arr[i][j]) << ": " << arr[i][j] << std::endl;
}
}
std::cout << std::endl << "Memory addresses for int **ptrptr:" << std::endl;
int **ptrptr = new int*[2];
for (int i=0; i<2; i++)
{
ptrptr[i] = new int[3];
for (int j=0; j<3; j++)
{
ptrptr[i][j] = arr[i][j];
std::cout << reinterpret_cast<void*>(&ptrptr[i][j]) << ": " << ptrptr[i][j] << std::endl;
}
}
// Cleanup
for (int i=0; i<2; i++)
{
delete[] ptrptr[i];
ptrptr[i] = nullptr;
}
delete[] ptrptr;
ptrptr = nullptr;
return 0;
}
Output:
Memory addresses for int arr[2][3]:
0x7ecd3ccc0260: 1
0x7ecd3ccc0264: 2
0x7ecd3ccc0268: 3
0x7ecd3ccc026c: 4
0x7ecd3ccc0270: 5
0x7ecd3ccc0274: 6
Memory addresses for int **ptrptr:
0x38a1a70: 1
0x38a1a74: 2
0x38a1a78: 3
0x38a1a90: 4
0x38a1a94: 5
0x38a1a98: 6
Notice how the memory addresses always increase by 4 bytes for arr, but for ptrptr there is a jump of 24 bytes between values 3 and 4.
A simple assignment can't create the pointer-to-pointer structure needed for type int **, which is why the loops were necessary in the above program. The best it can do is to decay the int[2][3] type into a pointer to a row of that array, i.e. int (*)[3]. That's what your auto ptr = arr; ends up as.
What is the type of [...]
Did you already try to ask the compiler to tell you the type of an expression?
int main()
{
int arr[2][3] = {{0,1,2}, {3,4,5}}; // <-- direct complete initialized here
auto ptr = arr; // <-- address assignment only
cout << "arr: " << typeid(arr).name() << endl;
cout << "ptr: " << typeid(ptr).name() << endl;
return 0;
}
I've to confess that the output
arr: A2_A3_i
ptr: PA3_i
seems to be not very readable at first glance (compared to some other languages), but when in doubt it may help. It's very compact, but one may get used to it soon. The encoding is compiler-dependent, in case you are using gcc, you may read Chapter 29. Demangling to understand how.
Edit:
some experimentation with some simple_cpp_name function like this rudimentary hack
#include <typeinfo>
#include <cxxabi.h>
#include <stdlib.h>
#include <string>
std::string simple_cpp_name(const std::type_info& ti)
{
/// simplified code extracted from "Chapter 29. Demangling"
/// https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html
char* realname = abi::__cxa_demangle(ti.name(), 0, 0, 0);
std::string name = realname;
free(realname);
return name;
}
will show you that auto &rfa = arr; makes rfa having the same type as arr which is int [2][3].
I need to implement a function that modifies an array. The new array may be a different size. cout prints 1. I understand what's wrong with this code but I just cannot figure out what the syntax is.
//tried this..
int reduce(int *array[])
{
*array = new int[1];
(*array)[0] = 6;
return 0;
}
//also tried this..
int reduce(int array[])
{
array = new int [1];
array[0] = 6;
return 0;
}
int main()
{
int a[1] = {1};
int *p = a;
reduce(&p);
cout << a[0];
return 0;
}
Don't understand your question correctly, but this is what you may do:
void reduce(int *a, int size)
{
for (int i =0; i < size; ++i) {
*(a+i) = 6; // or whatever value to want to
}
}
Call it this way:
int main(){
int a[5] = {1, 1, 1, 1, 1};
int *p = a;
reduce(p, 5);
for (int i =0; i < 5; ++i) { cout << a[i]<<endl; }
return 0;
}
EDIT
What you are trying to do can be vaguely done this way:
int * reduce (int **b, int size) {
*b = new int[size];
for (int i =0; i < size; ++i) {
*(*b + i) = 6;
}
return *b;
}
int main(){
int a[5] = {1, 1, 1, 1, 1};
int *p = a;
p = reduce(&p, 5);
cout << p[0];
cout << p[1];
cout << p[2];
cout << p[3];
cout << p[4];
delete [] p;
return 0;
}
But it still wont change where a is pointing to.
What you are trying to do is not possible with statically defined arrays.
When you use an array like
int a[1] = {1};
you cannot change the size of the array at run time, you cannot make it point to dynamically allocated memory. You may only access and modify the elements the array. That's it.
The function reduce changes where p points to but it does not change the elements of a.
If you want to modify the contents of a, you can simply use a as an argument, and set the values.
MODIFIED:
You want to modify array a, try this :
int reduce(int **array)
{
*array = new int[1];
(*array)[0] = 6;
return 0;
}
int main()
{
int *a = new int[1];
reduce(&a);
cout << a[0];
return 0;
}
First of all, the formal parameter int* array[] actually is the same as int** array (you can think of it as a two-dimensional array). This is probably not what you want.
The answer of #everettjf will only work if you do not change the size of the array. A possible solution (that completely replaces the array) would be
#include <iostream>
void print_array(int[],int);
int* reduce(int array[]) {
// get rid of the old array
delete[] array;
// create a new one
array = new int[7]{8,4,6,19,3,56,23};
// need to return the new address, so that
// the main function is informed on the new
// address
return array;
}
int main() {
// initialize array
int *a = new int[1]{4};
print_array(a,1);
// "change" array by completely replacing it
a=reduce(a);
print_array(a,7);
return 0;
}
// simply prints out the array; no error checking!
void print_array(int array[], int length) {
std::cout << "[";
for (int i = 0; i < length ; ++i) {
std::cout << array[i] << " ";
}
std::cout << "]" << std::endl;
}
In the reduce function, the initial array is completely deleted. Afterwards, you can create a new one (I chose to just use 7 random numbers). It is important to return that pointer back to the caller (the main method). Otherwise the a pointer in the main method would point to invalid
If you are not forced (by some kind of excercise, for example) to use arrays, you should look into http://en.cppreference.com/w/cpp/container/vector
The premise of your question is invalid. It is not possible to resize an array of automatic storage duration (aka a in main()) after its definition by ANY means in standard C++.
Dynamic memory allocations in either of your reduce() functions will not cause a in main() to be resized.
reduce(&p) will calls the first version of reduce() , which will then change p (so it points at the dynamically allocated memory) but not affect a.
If main() calls reduce(a) or reduce(p) (the two are equivalent, given the initialisation int *p = a) will change neither a nor p, but instead cause a memory leak.
The underlying problem, I suspect, is that you believe - incorrectly - that pointers and arrays are the same thing. They are actually different things, but can be used in the same way in various contexts. And your code is one of the contexts in which they cannot be used interchangeably.
If you want a resizeable array, use a static container (like std::vector<int>) and - if you want a function to resize it, pass it by reference. It manages its own memory dynamically, so is able to dynamically resize itself.