'C++ : Using for loop to declare pointer, shows segmentation fault
I am learning C++ pointer on array recently, what I'm trying to do is to use the for loop to declare batch of pointer and cout the address and value, My code is as below :
#include <iostream>
using namespace std;
void point_array();
int main ()
{
point_array();
}
void point_array ()
{
int array[20]={1,2,3,5,100};
cout << "size of whole array : " << sizeof(array) << endl;;
int k;
for (k=0;k<=4;k++){
int * p_[k];
p_[k] = &array[k];
cout << "Address of index \"" << k << "\" : " << p_[k] << endl;
cout << "value of index \"" << k << "\" : " << *p_[k] << endl;
}
}
Output matched what I expected as below :
size of whole array : 80
Address of index "0" : 0x7ffe82b77280
value of index "0" : 1
Address of index "1" : 0x7ffe82b77284
value of index "1" : 2
Address of index "2" : 0x7ffe82b77288
value of index "2" : 3
Address of index "3" : 0x7ffe82b7728c
value of index "3" : 5
Address of index "4" : 0x7ffe82b77290
value of index "4" : 100
But after I accidently add a line before for loop as below :
#include <iostream>
using namespace std;
void point_array();
int main ()
{
point_array();
}
void point_array ()
{
int array[20]={1,2,3,5,100};
cout << "size of whole array : " << sizeof(array) << endl;;
//these 2 lines
int & p_array = array;
cout << "Address of array : " << p_array << endl;
int k;
for (k=0;k<=4;k++){
int * p_[k];
p_[k] = &array[k];
cout << "Address of index \"" << k << "\" : " << p_[k] << endl;
cout << "value of index \"" << k << "\" : " << *p_[k] << endl;
}
}
It turns out a segmentation fault indicated on this line :
cout << "Address of index \"" << k << "\" : " << p_[k] << endl;
and I try to cout "k" before this line to debug, and it output "32767" instead of 0~4 I set in for loop.
It totally confused me... I'm wondering why will this fault happened after adding these 2 lines before for loop... Thank you!
Updated as below : Sorry for the typo,
int & p_array = array;
should be
int * p_array = array;
What I'm trying to do is to create bunch of pointer iteratively : p_0, p_1, p_2, p_3, p_4 and each of then match a single value's address in the array individually.
I think I misunderstand the operation of
int * p_[k];
p_[k] = &array[k];
due to the result seems same as what I expected.
Thanks for all of yours explanation!
BTW, is it possible to reach what I want(iteratively create variable/pointer) with C++?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
