Is it compulsory to initialize pointers in C++? - c++

Is it compulsory to initialize t in the following code, before assigning value to t? Is the code correct?
void swap(int *x, int *y)
{
int *t;
*t = *x;
*x = *y;
*y = *t;
}

You don't need pointer to begin with:
void swap(int *x,int *y)
{
int t; //not a pointer!
t=*x;
*x=*y;
*y=t;
}
int a = 10, b = 20;
swap( &a, &b); //<-----------note : Needed &
--
Or maybe, you want the following swap function:
void swap(int & x,int & y) //parameters are references now!
{
int t; //not a pointer!
t=x;
x=y;
y=t;
}
int a = 10, b = 20;
swap(a,b); //<----------- Note: Not needed & anymore!

is the following section of code correct?
Nopes! Your code invokes Undefined behaviour because you are trying to dereference a wild pointer.
int *t;
*t=*x; // bad
Try this rather
int t; // a pointer is not needed here
t=*x;
or this
int *t = x; // initialize the pointer

That code contains undefined behavior:
int *t;
*t=*x; // where will the value be copied?
Besides that it makes no sense - you need a temporary variable to store the value, not the pointer.
int t; // not a pointer
t=*x;
*x=*y;
*y=t;

It's correct for a pointer.
Only references need to be initialized upon declaration (or in a constructor for instance members).
EDIT: but you got errors in your code, you shouldn't be dereferencing your parameters (ie int *ptr = otherPtr; is fine, not int *ptr = *otherPtr;)

If you just want to make your pointer point to already-initialized data, then you don't need to initialize it. The way you do it, though, yes, you want to use one of the malloc functions to allocate enough heap space for an integer.
The proper, efficient way, to do swapping in C/C++ is
void swap(int *x, int *y) {
int *t = x;
x = y;
y = t;
}

You can find the right way of doing this here
#include <stdio.h>
void swap(int *i, int *j)
{
int t;
t = *i;
*i = *j;
*j = t;
}
Basically the reason has been explained to you by sharptooth but there you will find some more details and explanations about what happens in background when you do such a swap. Hope it helps to clear your ideas.

int *t;
*t=*x;
t is not pointing to any valid location to be able to dereference.
is it compulsory to initialize , before assigning value to pointer t.
Yes, initializing / assigning to point to a valid memory location. Else where would it point to. It might some point to garbage and lead to undefined behavior on dereferencing.

Related

How to define an alias to a pointer to an integer?

I am trying to run the following code, but I am getting the following error.
error: cannot declare pointer to 'int&'
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int *ptr = &x;
int &(*y) = ptr;
*y = 5;
cout << *ptr << endl;
return 0;
}
You declare references to pointers the same way you declare references to basic types.
Consider:
int main()
{
int i = 0; // int
int& ir = i; // int reference (reference to int)
int* ip = &i; // int pointer (pointer to int)
int*& ipr = ip; // int pointer reference (reference to pointer to int)
*ip = 5;
cout << *ipr << endl;
return 0;
}
If you just want a new pointer to the same region of memory, use:
int *y = ptr;
This not so much an "alias" in that if you change *ptr or *y, both will change, but if you change the pointers themselves, the other will not be updated.
If you actually do want a reference to a pointer, use:
int *&y = ptr;
int *ptr = &x;
pointer value has an address and a type of x.
when you typed code above, the value of ptr is an address of x, and ptr know the type of x.
int * (&y) = ptr;
the code above is declaring variable 'y' (type:int*, define:ptr's reference)
reference variables should be declared and defined simultaneously.
anyway, as a result, ptr and y are pointing same memory address.
you can easily think y is a nickname of ptr.
so you can access the variable 'x' by using y, instead of ptr.
v - a variable name.
&v - a variable that will be a reference of something.
*&v - a variable that will be a reference of a pointer to something
int *&v - a variable that will be a reference of a pointer to int
Or for a more interesting example,
(*&v)[5] - a variable that will be a reference of a pointer to an array of 5 something
int (*&v)[5] - a variable that will be a reference of a pointer to an array of 5 int

Unable to generate an error in a case of swap with help of pointers

I was trying to generate an error in swap code in C++. Interestingly, instead of an error, it successfully shows the opposite. My code look like this:
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int *tmp = x;
x = y;
y = tmp;
}
int main()
{
int u = 10;
int v = 20;
int * p = &u;
int * q = &v;
swap(*p, *q);
std::cout<<"u :-"<<u<<" v :-"<<v<<endl;
return 0;
}
The value of u and v got swapped. In this, I am passing pointer value instead of reference but the value gets swapped, How?
Exact code can be found at:
https://ideone.com/kMJHL6
swap(*p, *q);
Since the type of *p and *q are not int *, (it's just int) this code doesn't call your swap function. Instead, it calls the function std::swap, which is in standard C++ library, by function overloading resolving.
Your code has using namespace std; - your case is one of examples that show why you shouldn`t use it.
I think that you're calling the swap function of algorithm library, and not your function

C4700: uninitialized local variable

When I compile this code it says "error C4700: uninitialized local variable 'b' used". I'm not sure what I have to do now to fix this problem. I'm neither an IT student or technican but I very like to learn C++ and I'm learning it by myself. I've been on this for 1 day.
Many thanks
#include <stdio.h>
#include <iostream>
//A.
//1--
void InputArray(int *a, int &n)
{
printf("Insert n = ");
scanf("%d", &n);
a = new int[n];
for (int i=0; i<n; i++)
{
printf("Enter the key's a[%d] values: ", i);
scanf("%d",&a[i]);
}
}
void main()
{
int *b, m;
InputArray(b, m);
}
b is passed by value, which means a copy will be made, but since it's not initialized, you get the warning. Simply initialize it:
int *b = nullptr;
or
int *b = NULL;
If you want the function to modify the caller's variable, then pass by reference:
void InputArray(int *&a, int &n)
^
Your version passes the uninitialised pointer by value; the function modifies a local copy of it, but leaves b in its uninitialised state.
The pointers are not default initialized, so your variable b is uninitialized, this is the source of error. You have to initialize this variable to fix this:
void main()
{
int *b = NULL, m;
InputArray(b, m);
}
After you fix this there is additional problem in your code. It seems from the way you call a function that you expect to persistently change pointer b passed into it, so that b will point into memory allocated with new after function returned. But you pass a pointer by value what means changes made in function will not be reflected in original variable b which will still point to what it pointed before the call to a function. (the array will be allocated inside function and will stay in memory after function returned but you will leak this memory as b won't point into it). To fix this you have to pass pointer by reference:
void InputArray(int*& a, int& n)
Also: where is delete? Remember: mapping new to delete is bijection: every new corresponds to single delete placed somewhere in code.
First of all, did you learn how to use an pointer correctly ? because if you know how to use pointer u should know that when you declare a pointer you need to be initialized to NULL before you can use it, correct me if i'm wrong.
Example
int *b = nullptr;
int *b = NULL;
int *b = 0;
int *b(0);
It's all the same thing but in an different way

Diff Between Call By Reference And Call By Pointer [duplicate]

This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 9 years ago.
Can any one tell me the exact diff between call by pointer and call by reference. Actually what is happening on both case?
Eg:
Call By Reference:
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
swap(a, b);
Call By Pointer:
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
swap(&a, &b);
The both cases do exactly the same.
However, the small difference is, that references are never null (and inside function you are sure, that they are referencing valid variable). On the other hand, pointers may be empty or may point to invalid place in memory, causing an AV.
Semantically these calls have identical results; under the hood references are implemented with pointers.
The important difference between using references and pointers is with references you have a lot less rope to hang yourself with. References are always pointing to "something", where as pointers can point to anything. For example, it is perfectly possible to do something like this
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
++x;
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
And now this code could do anything, crash, run, have monkeys fly out of your noes, anything.
When in doubt, prefer references. They are a higher, safer level of abstraction on pointers.
In your example, there is no difference.
In C++ reference is implemented using pointers.
Edit: for those who believe reference can't be NULL:
int calc(int &arg)
{
return arg;
}
int test(int *arg)
{
return calc(*arg);
}
Guess, what will be the result for test(0)?
Your code is C++ code. In Java there are no pointers. Both examples do the same thing, functionally there is no difference.
I don't know exactly why this was tagged jave as there are no pointers. However, for the concept you can use both pointers and reference interchangeably if you are working on the value attribute. for example i=4 or *i=4. The advantage of using pointers is that you can manipulate the adress itself. Sometimes you will need to modify the adress (point it to something else ...) this is when pointers are different for reference; pointers allow you to work directly on the adress, reference won't

about c++ cast question

#include <stdlib.h>
int int_sorter( const void *first_arg, const void *second_arg )
{
int first = *(int*)first_arg;
int second = *(int*)second_arg;
if ( first < second )
{
return -1;
}
else if ( first == second )
{
return 0;
}
else
{
return 1;
}
}
In this code, what does this line mean?
int first = *(int*)first_arg;
I thinks it's typecasting. But, from
a pointer to int
to a
pointer to int
little confused here.
Thanks
?
first_arg is declared as a void*, so the code is casting from void* to int*, then it de-references the pointer to get the value pointed from it. That code is equal to this one:
int first = *((int*) first_arg);
and, if it is still not clear:
int *p = (int *) first_arg;
int first = *p;
It is casting a void pointer to a integer pointer and then dereferencing it.
Let's think about it in steps.
void *vptr = first_arg;
int *iptr = (int *)first_arg; // cast void* => int*
int i = *iptr; // dereference int* => int
So, you're specifying the type of data the pointer points to, and then dereferencing it.
int first = *(int*)first_arg;
It's the same as:
int* ptr_to_int = (int*)first_arg;
int first = *ptr_to_int;
That first line does 2 things: it casts the void pointer to an int* and access that memory location to retrieve the value that's there.
There are already many answers to your question, this is more like a comment, something that you will inevitably learn in your quest on mastering C and C++.
Your function is too long. From its name, I predict what you really need is:
int int_sorter( const void *first_arg, const void *second_arg )
{
return *(int*)first_arg - *(int*)second_arg;
}