• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

nvm

And I thought picking up C++ from Java would be easy, until I ran into pointers 😛

Anyways, here's the empirical problem code:

int main(void)
{
int* i3 = new int;
*i3 = 25;
someFunction(i3);

}

someFunction(int* i)
{
cout << *i; //works. Prints 25;
int x = (*i); /*Apparently causes a seg fault. When I comment it out, the seg fault doesn't occur. I also tried making a pointer and assigning it's value to *i (ie: *newPointer = *i), but that had the same result. Google is useless. Any ideas? */
}
 
I believe you need to use the & operator instead of * in order to dereference the pointer into your int x. I could be wrong because I haven't touched C++ in a few years, but I think that's right.
 
Originally posted by: Crusty
I believe you need to use the & operator instead of * in order to dereference the pointer into your int x. I could be wrong because I haven't touched C++ in a few years, but I think that's right.

To my knowledge & = adressOf, * = dereference, but I'll give it a shot.

Update: Nope. int x = &i; gives a compile time error. Conversion from int** to in*
 
nvm. Looks like the seg fault was originating from another segment of someFunction, which makes a lot more sense. I still don't get why commenting out the lines above prevented it, but it works now. Thanks anyway!
 
Nah, the dereferencing is correct. & takes the address, so &i would give you the location where the pointer itself is stored.

I honestly can't see why that code would cause a segfault. You don't need the parens around *i by the way. Parens are only useful in expressions for casting or controlling precedence of operations.

Edit: heh, that was fast 🙂. Commenting out the lines would have shifted the code and changed the memory layout, which could account for the difference in behavior. That's the beauty of pointers 😉.
 
Originally posted by: Markbnj
Nah, the dereferencing is correct. & takes the address, so &i would give you the location where the pointer itself is stored.

I honestly can't see why that code would cause a segfault. You don't need the parens around *i by the way. Parens are only useful in expressions for casting or controlling precedence of operations.

Edit: heh, that was fast 🙂. Commenting out the lines would have shifted the code and changed the memory layout, which could account for the difference in behavior. That's the beauty of pointers 😉.

I know but by that point I was confused as hell, so I figured I might as well play it safe if the compiler was somehow messing it up.
 
Back
Top