This question already has answers here:
If an array name is treated as a pointer, why do I get a compile time error of Lvalue required when incrementing an array?
(3 answers)
Closed 9 years ago.
int main()
{
int a[]={2,3,4,5,6};
int j;
for(j=0;j<5;j++)
{
printf("%d\n",*a);
a++;
}
return;
}
gives Lvalue required error
but
int main()
{
int a[]={2,3,4,5,6};
int *p,j;
p=a;
for(j=0;j<5;j++)
{
printf("%d\n",*p);
p++;
}
return;
}
doesn't.
why????
So I dont understant that even though in a[], a is treated as a pointer so why cant we increment it just like a pointer
Because array name is not a separate memory cell. It is a named memory extent. So it is not clear where to store the incremented value.
Pointers and arrays are not completely interchangeable.
int main ()
{
int var[MAX] = {10, 100, 200};
for (int i = 0; i < MAX; i++)
{
*var = i; // This is a correct syntax
var++; // This is incorrect.
}
return 0;
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value. The reason for this is that var is a constant that points to the beginning of an array and can not be used as l-value.
Because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified
Related
This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 5 years ago.
I was looking at this code and understood pretty much all of it except one thing:
what does Arr1++ means?
What does it do to the array? since Arr1 is not just a normal variable like int..
bool theSameElements(int Arr1[], int Arr2[], int size)
{
int temp;
if (size == 0)
{
return true;
}
for (int i = 0; i < size; i++)
{
if (Arr1[0] == Arr2[i])
{
temp = Arr2[i];
Arr2[i] = Arr2[0];
Arr2[0] = temp;
Arr1++;
Arr2++;
return theSameElements(Arr1, Arr2, size - 1);
}
}
return false;
}
Any array passed as function parameter is implicitly converted / decays to a pointer of type int*. Now the Arr1 is a pointer pointing to the first array element namely Arr1[0]. This is known as the Array-to-pointer decay. Applying the post-increment operator:
Arr1++;
increments the pointer value by the size of the data it points to so now it points to the second array element Arr1[1].
That being said you should prefer std::array to raw arrays and smart pointers to raw pointers.
So what you need to know is that Arr, in this case, is the pointer to the array. So when you do Arr++ you are basically incrementing the pointer to this array.
Function parameters which appear to have array type, in fact have pointer type. int foo[3] and int foo[], in the context of a function parameter list (and only in that context), are exactly the same as int* foo. Because of this, you can do things to them that you wouldn't ordinarily be able to do to arrays, such as reassign their values.
This question already has answers here:
What is a dangling pointer?
(7 answers)
Closed 5 years ago.
Normally a scope of an array in a function ends with it. But if I allocate beforehand then it perfectly returns the array. So what's the difference between allocating array or declaring array?
I am writing the code and the place where I am confused. Is it because of dynamic memory allocation of the first declaration or something else. Can someone elaborate please?
#include <bits/stdc++.h>
#define N 10
using namespace std;
int * get_array() {
int * p = new int[N];
//|--- by declaring like this, the array was perfectly returned.
int p[N];
//|--- but is case of this declaration the array returned showed garbage value in the main function.
for(int i = 0; i < N; ++i) p[i] = i;
return p;
}
int main(int argc, char const *argv[])
{
int * M = get_array();
for (int i = 0; i < N; ++i) {
cout << M[i] << endl;
}
return 0;
}
In the second case the array is created in the heap of the function, so when you exit the function, that array doesn't exists anymore.
In the first case, you're reserving memory space to put your array, so isn't local to the function per se, and you must handle its destruction
This question already has answers here:
Error when passing pointer to array of structs
(5 answers)
Closed 7 years ago.
When I run this code it gives me a segmentation fault error.
#include <stdio.h>
#include <stdlib.h>
void function(int **A);
void main()
{
int *A = NULL;
int i = 0;
A = (int *) malloc(70 * sizeof(int));
function(&A);
for (i = 0; i < 10; i++){
printf("A is : %d\n", A[i]);
}
free(A);
}
void function(int **A){
int i = 0;
for (i = 0; i < 10; i++){
*A[i]=i*2;
}
}
*A[i]=i*2;
should be
(*A)[i]=i*2;
because you need to dereference the pointer before applying the array subscript operator([]). In your current code, [] has more precedence than the dereference operator(*) as per the operator precedence table. So you need parenthesis.
Other things to note:
In C, don't cast the result of malloc
Always check the result of malloc to see if it was successful
It would have been simpler if you pass a pointer to the array,i.e, use
function(A);
instead of passing the address of A and change function's signature to:
void function(int *A)
and using
A[i]=i*2;
in the for loop in function. Since A in function points to the address of the first element of the array A in main, any change you make to the memory where A in function points to, will be reflected in the array A in main.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
#include<iostream>
using namespace std;
int *Arr(int y,int size){
int arg[size];
for(int i=size-1;i>=0;i--){
arg[i]=y%10;
y=y/10;
}
return arg;
}
int main(){
int *p=Arr(2587,4);
for(int j=0;j<4;j++){
cout<<p[j]<<" ";
}
return 0;
}
> Blockquote
I dont why this isn't working ...I'm trying to back an array but the problem is in the second digits.Can somebody help ;) thanks
The problem is you are putting your result into a local array that is destroyed when the function ends. You need to dynamicaly allocate the array so that its life-span is not limited to the function it was created in:
#include<iostream>
using namespace std;
int *Arr(int y, int size)
{
// This local array will be destroyed when the function ends
// int arg[size];
// Do this instead: allocate non-local memory
int* arg = new int[size];
for(int i = size - 1; i >= 0; i--)
{
arg[i] = y % 10;
y = y / 10;
}
return arg;
}
int main()
{
int *p = Arr(2587, 4);
for(int j = 0; j < 4; j++)
{
cout << p[j] << " ";
}
// You need to manually free the non-local memory
delete[] p; // free memory
return 0;
}
NOTE:
Allocating dynamic memory using new is to be avoided if possible. You may want to study up on smart pointers for managing it.
Also, in real C++ code, you would use a container like std::vector<int> rather than a builtin array
Of course it is not working.
At best, the behaviour is undefined, since Arg() is returning the address of a local variable (arg) that no longer exists for main(). main() uses that returned address when it is not the address of anything that exists as far as your program is concerned.
There is also the incidental problem that int arg[size], where size is not fixed at compile time, is not valid C++. Depending on how exacting your compiler is (some C++ compilers reject constructs that are not valid C++, but others accept extensions like this) your code will not even compile successfully.
To fix the problem, have your function return a std::vector<int> (vector is templated container defined in the standard header <vector>). Then all your function needs to do is add the values to a local vector, which CAN be returned safely by value to the caller.
If you do it right, you won't even need to use a pointer anywhere in your code.
This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 8 years ago.
i have simple main that called simple methods with array as parameter
the size in the array is right , but then when i try to print the array im getting different
sizeof array :
int bubbleSort(int arr[]) // yeah i know this sort is not complete
{
int arrSize = sizeof(arr); // HERE IS SIZE IS 4
bool bSorted = true;
while(bSorted)
{
for(int i=0;i<arrSize;i++)
{
if(arr[i]>arr[i+1])
{
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
}
bSorted = false;
}
return 1;
}
int main(int argc, char* argv[])
{
int arr[] = {4,3,7,8,9};
bubbleSort(arr);
int sOf = sizeof(arr); // HERE THE SIZE IS 20 ????
for(int j=0;j < sOf ;j++)
{
printf("%d",arr[j]);
}
return 0;
}
You cannot pass arrays* by value as function parameters (nor return them in such fashion). The syntax void f(int a[]) is merely syntactic sugar that is in every aspect identical to void f(int * a), and the function parameter is a pointer, not an array. So you end up measuring the size of the pointer.
The alternative syntax may serve as a loose kind of documentation of intent, signalling that you plan to call this function with the address of an array element, but there is no actual difference to the pointer syntax.
*) Array types and function types are both constrained thus, which is why people often say that they are not first-class citizens of the type system.
Due to the language being stupid, this:
int bubbleSort(int arr[])
actually means this:
int bubbleSort(int* arr)
So sizeof(arr) is the size of a pointer.