Segmentation fault when passing user input to a pointer to an array
Hi Everyone, I am working with pointers. I am tryin to input a value into a double array, and then output this value not with the double array variable itself but instead, I would like to use the pointer to the double array variable to output the user's input.
Here is my code. #include <iostream> using namespace std; // cin and cout int main() { double weight[50]; // variable array weight of type double double * p_pw; // pointer to weight pw p_pw = &weight[50]; // pw is assigned the address of the weight array cout << "input a value for your weight please: " << endl; cin >> weight[50]; // store input in weight array * p_pw = weight[50]; cout << " The weight that you inputed is \n" ; // cout << * p_pw << endl; // should return the input from user return 0; } // end main The program compiles fine, the segmentation fault error is listed right after I submit input. Here is a image of the error message I recieve. jonathan@ubuntu:~/c++practice/chapter4$ ./a.out input a value for your weight please: 23 Segmentation fault |
Quote:
p_pw = weight; or equivalent p_pw = &weight[0]; Your version sets p_pw to point to the address of the 51'st element of a 50 element array (in other words to the next object on the stack after that array). Quote:
Whatever it was should not be done that way. An array declared with size 50 has elements 0 through 49. It does not have an element 50. Edit: On review, I think I do have a guess what you may have been trying to do: Code:
#include <iostream> * p_pw = weight[50]; Even corrected to 49 instead of 50, that would confuse the example. The earlier code makes *p_pw the same object as weight[50]. Changing one of them changes the other. Copying one to the other is redundant. The important change I made was to use the last element of the array instead of one past the last element. Since your comments obscured your intention (if I'm now guessing it correctly), I also changed those. |
All times are GMT -5. The time now is 03:50 AM. |