Illegal hardware instruction on a c program compiled on Mac - c++

I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int * x;
*x=10;
cout << fun(x);
return 0;
}

Pointers are just pointers. In your code there is no integer that you could assign a value to.
This
int * x;
Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:
*x=10;
You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? There is no int where x points to, because x doesnt point anywhere. Your code has undefined behavior. Output could be anything.
If you want to assign 10 to an int you need an int first. For example:
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int y = 0;
int * x = &y;
*x=10;
cout << fun(x);
return 0;
}
This assigns 10 to y. The cout is still printing the value of x, which is the adress of y. It does not print the value of y. Not sure what you actually wanted.

The problem is that in your program the pointer x is not pointing to any int variable. So first you have to make sure that the pointer x points to an int object as shown below.
You can sovle this as shown below:
int i = 0; //create the int object to which x will point
int *x = &i; //make x point to variable i
*x = 10; //dereference the pointer x and assign 10 to the underlying variable i
cout << *fun(x); //this prints 10

Related

Passing Pointers By Reference vs Passing Pointers Into Functions

It's been a while since I've coded anything in C++. While I was trying to help another person as a CIS Tutor, he wanted to know why it's necessary to have an ampersand next to a pointer to an int.
I figured that if you were to pass a pointer by reference and you point to something else, the main knows after you passed that val will equal to whatever you set it equal to.
There will be an example below will demonstrate what I'm trying to say.
Is this correct?
//main function
int variable = 0;
int* val = &variable;
function1(val);
cout << *val << endl;
function2(val);
cout << *val << endl;
//Passing in a pointer with reference.
void function1(int*& value)
{
int variable = 9;
value = &variable;
}
//Passing in a pointer without reference.
void function2(int* val)
{
int variable = 9;
value = &variable;
}
My assumption is that the program will output 9 instead of 8 or 0. I hope this give you guys a clear picture of what I'm trying to ask.
The difference between passing the values and passing the reference is the same with pointers as with other values (actually pointers are nothing special they just hold numbers that sometimes are adresses of other objects).
With int:
void foo(int x) { x = 1; }
void bar(int& x) { x = 2; }
int main() {
int y = 5;
foo(y);
std::cout << y; // prints 5
bar(y);
std::cout << y; // prints 2
}
Now with pointers:
void foo(int* x) { x = 0; }
void bar(int*& x) { x = 0; }
int main() {
int y = 42;
int* z = &y;
foo(z);
std::cout << z; // prints the address of y
bar(z);
std::cout << z; // prints 0
}
Note that your function1 is broken, because when you call it
int* y;
function1(y);
std::cout << *y; // **baaam**
// the value y points to is already gone
the int inside the function ends its lifetime when the function returns and the caller cannot use the value in any meaningful way. Note that in this particular example you would probably get the "correct" value printed, but that is just by coincidence and dereferencing y after passing it to function1 is undefined behaviour.

Converting C++ code to C, array of structs

I'm converting C++ code to C for an exercise (we are just learning c++ now), and I am lost at this part.
First, the c++ code:
Point()
{
x = y = 0;
}
main()
{
const int N = 200;
Point *A = new Point[N], sum;
}
Here's my C version of it:
struct Point //constructor
{
int x;
int y;
} Point;
main()
{
int N = 200;
Point* A = malloc(N * sizeof(*Point[]));
}
That should give you an idea of what I'm trying to do. Questions:
Is sum in the C++ code the C++ sum function, or is it aPointstruct`?
For allocating the memory in C, I don't think my method works. Should I do a for loop where it mallocs each index of A[]? (A should be an array of Point structs).
Any assistance would be greatly appreciated.
EDIT: Got asked for the context of the code.
Here's the whole C++ program:
#include <iostream>
// a point on the integer grid
struct Point
{
// constructor
Point()
{
x = y = 0;
}
// add point componentwise
void add(const Point &p)
{
x += p.x;
y += p.y;
}
// print to standard output
void print() const
{
std::cout << "[" << x << "," << y << "]" << std::endl;
}
// data
int x, y;
};
int main()
{
const int N = 200;
Point *A = new Point[N], sum;
for (int i=0; i < N; ++i) {
sum.print();
A[i].x = i; A[i].y = -i;
sum.add(A[i]);
}
sum.print();
delete [] A;
}
Ultimately, I have to emulate that in C. Currently stuck at the question I asked: re: what does that line do. I have since figured out that I need to make a struct of Point called sum, and print that after running the add function on all its members.
In your C version:
struct Point //constructor
{
int x;
int y;
} Point;
should be:
typedef struct //constructor
{
int x;
int y;
} Point;
Because in your case, you defined a global variable named Point.
And, the C programming language has the const keyword as C++ as well, so you can do this in the C language:
const int N = 200;
And the C++ code:
Point *A = new Point[N], sum;
In C version, should be:
Point *A = malloc(N * sizeof(Point)), sum;
But in this version, the memory isn't initialized by zero.
You can use the calloc function instead of the malloc to allocate memory and initialize it with zero:
Point *A = calloc(N, sizeof(Point)), sum;
Then back to your question:
Is sum in the c++ code the c++ sum function, or is it a Point struct?
It is a Point type variable.
For allocating the memory in C, I don't think my method works. Should I do a for loop where it mallocs each index of A[]? (A should be an array of Point structs).
No, there's no necessary to write a for loop. The malloc function will do exactly what you want.
Is sum in the c++ code the c++ sum function, or is it a Point struct?
In your case, it is a Point struct.
Point *A = new Point[N], sum;
is equivalent to:
Point *A = new Point[N];
Point sum; //I have no idea why naming is sum
If you need Point* for sum, you should write it in the following way:
Point *A = new Point[N], *sum;
For allocating the memory in C, I don't think my method works
It does not work, syntax is wrong. Try:
EDIT: thanks to #mch, you should not use cast for malloc.
typedef struct Point Point;
Point* A = malloc(N * sizeof(Point));

How does one pass by pointers with two arguments in function?

Can someone demonstrate how to pass by pointers using one function that takes two arguments from two variables as input?
#include <iostream>
using namespace std;
int passPoints(int *x, int *y)
{
int y = *x * *y;
return(y);
}
int *X, *Y;
int main()
{
cout<<"enter two values: ";
cin>>*X;
cin>>*Y;
cout<<"RESULT = "<<passPoints(X,Y);
return 0;
}
Having trouble.
Like this:
int X, Y;
int main()
{
cout<<"enter two values: ";
cin>>X;
cin>>Y;
cout<<"RESULT = "<<passPoints(&X,&Y);
return 0;
}
The biggest problem in your code (if it is not a typo when you are extracting for question) is, int* X and Y are null pointer and the location they are pointing at are not valid for you to update. You need to make sure that these pointers are pointing to a valid memory location, either by:
int x, y;
int* xPtr = &x;
int* yPtr = &y;
passPoints(xPtr, yPtr);
or simply
int x, y;
passPoints(&x, &y);
now the pointers received by passPoints() are valid pointers

Getting segmentation fault with c++ pointers

So I'm trying to familiarise myself with c++ pointers by running the following code.
#include <iostream>
using namespace std;
int main(void){
int* x;
cout << &x << endl;
return 0;
}
which works fine and prints the pointer value of x but
#include <iostream>
using namespace std;
int main(void){
int* x;
*x = 100;
cout << &x << endl;
return 0;
}
gives me a segmentation fault when I try to tun it. Why is this? I don't see how that extra line should change anything about the address of x.
You did not allocate an object which you are going to assign.
int* x;
The value of x is unspecified and can be any arbitrary value. So the next statement
*x = 100;
is invalid.
You have to write
x = new int;
*x = 100;
Or
x = new int( 100 );
Or even
x = new int { 100 };
provided that your compiler supports the list initialization for operator new which was introduced in the C++ 2011..
and prints the pointer value of x but
Not exactly.
std::cout << &x; it prints x's address (the pointer's address);
std::cout << x; prints the address, x points to;
std::cout << *x; prints what x points to;
int* x;
*x = 100;
Here, x is just a pointer, you need to allocate memory for the 100. For example
int* x = new int;
*x = 100;
std::cout << *x;
Or just
int* x = new int( 100 );
std::cout << *x;
Without allocating memory and leaving x uninitialized, by *x = 100 you're trying to change some random memory, which leads to undefined behavior.
You have undefined behaviour.
Your first example is fine since &x (which has type int**) is the address of a stack allocated pointer. One of the << overloads in cout is defined to output that correctly.
In the second example, you are dereferencing a pointer that is not pointing to anything. That's undefined behaviour; hence the crash. If you'd written
int y;
int* x;
x = &y;
*x = 100; /*this means that y is now 100*/
then all would have been well since now x is pointing to something.

Passing a pointer address

int main()
{
int x = 2, y = 4;
func(&x, &y);
printf("%d %d\n", x, y);
return 0;
}
void func(int *x, int *y)
{
int *temp;
temp = x;
x = y;
y = x;
}
Hi
For this code i have no idea why the output is 2 4 instead of 4 4. Since x = y in func() means x now points to the address of y, and y = x in func() means y now points to the address of x (which is y), both variables are now pointing to y already.
Many thanks!
The answer is simple: You change the pointer values inside func - but not the values they point at. I guess you'd like to swap the variables (due to the temp var).
This code should work (swapping values):
void func(int *x, int *y)
{
int temp = *x; // dereferencing the pointer to get the value it points at.
*x = *y;
*y = temp;
}
Too keep your initial expectations (which don't make any sense code wise due to the second assignment):
void func(int *x, int *y)
{
*x = *y;
*y = *x;
}
Nope, func() will receive copies of those addresses and this won't affect the variables outside the function - all changes done to variables local to func() will be discarded once func() exits.
You are just temporarily assigning the address of 'x' to the address of 'y' within func. In order to make the assignment, you need to dereference your pointers.
*x = *y;
*y = *x;
Try this
#include <iostream>
using namespace std;
void func(int *x, int *y);
int main()
{
int x = 2, y = 4;
func(&x, &y);
//printf("%d %d\n", x, y);
cout << "X - " << x << endl;
cout << "Y - " << y << endl;
return 0;
}
void func(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
You're making copies of the passed in pointers, they are local to your function. Any change you make to them doesn't affect the outside. You should capture the pointers by reference &.
void func(int*& x, int*& y){
// as before...
}
Now the changes inside the function will be correctly reflected outside of it. On problem remains though. You're passing in the address of local variables, and attempt to change their pointers - that doesn't work. When you take the address of a variable &x, you make a new temporary pointer, which can't be converted to a reference-to-pointer.
Do this instead:
int main(){
int x = 2, y = 4;
int *px = &x, *py = &y;
func(px, py);
printf("%d %d\n",*px,*py);
}
Edit: If you instead want to swap / set the values of x and y and not just some pointers, do as the other answers state.
The problem is that you're trying to write your own version of std::swap. This will work:
int x = 2, y = 4;
std::swap(&x, &y);
printf("%d %d\n", x, y);
return 0;