I am unable to understand the following code in ะก, using pointers
#include <stdio.h>
#include <stdlib.h>
int bags[5]={20,5,20,3,20};
int *next();
int main()
{
int pos=5;
*next()=pos;
printf("%d,%d,%d",pos,*next(),bags[0]);
}
int *next()
{
int i;
for(i=0;i<5;i++)
if(bags[i]==20)
return(bags+i);
printf("Error!");
}
Can anyone explain why the ans is 20,5,20.
The output of the program will is,
5,20,5
because
if(bags[i]==20)
return(bags+i);
returns pointer to bags[0] since bags[0]==20 and return is a pointer to it and
*next()=pos;
writes pos value to the address pointed by next() returned address, i.e. bags[0]=pos=5
The function next returns a pointer to the first array element equal to 20.
So, *next()=pos; will modify the first element of the array from 20 to 5.
Then it is simple to understand why the output is 5,20,5: since pos is five, *next() returns 20 and bags[0] is 5 as explained above.
The output is 5,20,5.
Note: int *next(); ==> next() is a function that returns int*.
[1] The call to next() from the line *next() = pos;. C evaluates the function from left so next() gets called first. Because of if (bags[i] == 20), the function next() returns bags+i which is simply bags since i is 0 at the moment. So next() returned the address of bags which means *next() is nothing but the pointer to bags[0]. So bags[0] becomes 5.
[2] When the execution comes to this line: printf("%d,%d,%d",pos,*next(),bags[0]);, it prints value of pos i.e 5, value of *next() which is 20 as next() returned the address of bags[0].
[3] *next() prints 20 because, this time next will return the address of bags[2] since bags[0] got assigned with the value of pos in the line before the printf().
[4] And finally, bags[0] is 5. See the explanation in [1].
Related
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.
Edit:
Why is if statement not working in this case? It seems logic that it should work...
My main.c file:
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7
int main(void)
{
int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };
maxValue(array1, Size);
return 0;
}
My functions.h file:
#pragma once
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int maxValue(const int *, int);
#endif
My functions.c file:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
int maxValue(const int *array1, int Size)
{
int max = array1[0];
if (max < array1[Size]) {
Size++;
max = array1[Size];
}
printf("Max value: %d \n", max);
}
Why is if statement not working in this case? It seems logic that it should work...? Because here
if (max < array1[Size]) { }
Size is defined as 7 and you are comparing array1[0] with array1[7] i.e 11 < 4 -> false, hence it doesn't enter into if block, so the last printf executes and that prints max. But its not a correct logic if if blocks becomes true then further Size++ will cause accessing out of bound array elements which cause undefined behavior.
int maxValue(const int *array1, int Size)
{
int max = array1[0];
if (max < array1[Size]) { /* 11 < 4 false, skips if block */
//Size++; /* this is wrong as Size++ here and next accessing array1[Size] cause UB due to accessing out of bound array element */
max = array1[Size];
}
printf("Max value: %d \n", max); /* max is stills array1[0] i.e 11 */
}
Let's simulate what the CPU does when it enters the maxValue function with those arguments. 1. The variable max is assigned the value of array1[0], which is 11.
2. If max (11) is less than array1[7] (4). It is not, so the if block is not executed.
3. Print max: print 11.
Another thing: Your program causes undefined behaviour. Let's take an example where array1[0] is 3, instead of 11. The if block will be executed (3 < 4), so:
Size is incremented to 8.
max is assigned array1[8]. Since the last index in array1 is 7 (that is how you declared the array), you are accessing a memory adress which you are not supposed to access. This is undefined behaviour.
The names maxValue() and max are misleading and confusing what you are trying to do. lastValue() and last would make much more sense.
However what you are trying to do makes no sense in C because arrays are of known length, so you can access the last element directly:
int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };
int array_length = sizeof(array1) / sizeof(*array1) ;
printf("Lastvalue: %d \n", array1[array_length - 1] ) ;
However you cannot do this in a function because arrays are not first class data types in C and when passed to a function will "degrade" to a simple pointer without any information regarding the size of the array pointed to. The calling function having the size information must pass that too (as you have done, but then appeared to get very confused):
void printLast( int* array, int length )
{
printf( "Lastvalue: %d \n", array1[length - 1] ) ;
}
It is difficult to see why you thought you might need any other code or what your maxValue() function is intended to achieve. The "logic" which you say "should work" is thus:
If value of the first array element is less than the value of the last array element, then print the undefined value one past the end of the array; otherwise print the first element of the array.
If you wanted to print the last element, then you simply print it, the value of the first element has nothing to do do with it. Either way you should not index past the end of the array - that value is undefined.
Note I'm using C not C++. I'm working on a program that will take a 2d-array and count the numbers of non-spaces in a subarray. Such as lines[0][i] <-- iterating over line[0][0] - line[0][n]. However, I'm having difficulty getting the function to accept the 2d-array.
Here is my code:
pScore[0]=letters(pLines, 0);
This is the actual function. pScore[] is another array, but a 1d one. pLines is a 4 by 200 2d-array.
int letters(char line[][], int row)
{
int i = 0;
int n = n;
int results = 0;
for( i = 0; i < (sizeof(line)/sizeof(line[0])); i++ )
{
if( !isspace(line[row][i]) )
results++;
}
return results;
}
When I do this it gives me "formal parameter number 1 is not complete". If I remove the second [] from it, the code runs but gives the worng number of non-space characters.
Taking from the comments above, and your function parameter list:
int letters(char line[][], int row)
You violate one primary tenant of passing a 2D array to a function. Specifically, you must always provide the number of columns contained in the array. e.g.
int letters(char line[][5], int row)
char line[][5] is an appropriate parameter. However, whenever you pass an array as a function parameter, the first level of indirection is converted to a pointer. (you will often here this referred to as "pointer-decay", though that is a bit of a misnomer). Therefore a proper declaration that makes this clear is:
int letters(char (*line)[5], int row)
line, after conversion, is a pointer-to-an-array of 5-int. While you can pass the array as line[][5], that is not nearly as informative as (*line)[5]. Let me know if you have any questions.
Numbers Instead of Characters
It is hard to tell what is going on without seeing the remainder of your code. However, I suspect that you are confusing the numerical value and the ASCII character value for the contents of your array. (e.g. character '0' = decimal 48 (0x30 (hex), '1' = 49, 'a' = 97, etc..). See ASCIItable.com
You you pass an array to a function it decays to a pointer. That means char line[][] should really by char (*line)[SIZE_OF_SECOND_ARRAY].
It also means the sizeof trick will not work, as doing sizeof on the pointer line will just return the size of the pointer and not what it points to, you need to explicitly pass the size as an argument to the function.
You need tell function the number of columns of 2d array. Here may help you.
I am not sure if the following statement works with you
for( i = 0; i < (sizeof(line)/sizeof(line[0])); i++ )
where sizeof(line) will be 4 or something like that depends on your platform because "line" is a pointer and you get the size of pointer itself.
Correct me if I am wrong.
In this case, you should pass column number as row's.
I usually program in java and recently watching some c codes.
I came up across this program and I don't know how this pointer thing is working.
I know pointer stores the address and all but couldn't make it through the program.
Please tell how is the output coming as 8 ?
#include <stdio.h>
int fun(int n, int * f_p) {
int t, f;
if (n <= 1) {
*f_p = 1;
return 1;
}
t = fun(n - 1, f_p);
f = t + *f_p;
*f_p = t;
return f;
}
int main() {
int x = 15;
printf("%d\n", fun(5, &x));
return 0;
}
What you have here is a recursive function that calculates the i-th element of a Fibonacci sequence (indexing from 0). Each recursive iteration returns two values: the i-th Fibonacci number and the (i-1)-th (previous) Fibonacci number. Since a function in C can only return one value (well, unless you use a struct as return type), the other value - the previous Fibonacci number - is returned to the caller through a pointer parameter f_p.
So, when you call fun(5, &x), the function will return 8, which is the 5-th Fibonacci number, and it will also place 5 into x, which is the previous (4-th) Fibonacci number.
Note that the initial value of x does not matter. That 15 does not play any role in this program. Apparently it is there as a red herring.
If you know what a Fibonacci sequence is, you know that the next element of the sequence is the sum of the two previous elements. This is why the function is written to "return" two elements of the sequence to the caller. You might not care about that previous value in the top-level caller (i.e in main), but the nested recursive calls do need it to calculate the next number. The rest is pretty straightforward.
Step by step:
fun gets called with a 5 and the x address
fun calls fun with a 4 and f_p, which is the x address
fun calls fun with a 3 and f_p, which is the x address
fun calls fun with a 2 and f_p, which is the x address
fun calls fun with a 1 and f_p, which is the x address
fun got called with a 1 so the if condition is true, puts a 1 in the variable pointed by f_p(x) and returns 1
this returned value is assigned to the t of the fun(2,f_p), f is f = t + *f_p which is 1+1 -> f=2;
the variable pointed by f_p is set to t so x=1, returns f so it returns 2
this returned value is assigned to the t of the fun(3,f_p), f is f = t + *f_p which is 2+1 -> f=3;
the variable pointed by f_p is set to t so x=2, returns f so it returns 3
this returned value is assigned to the t of the fun(4,f_p), f is f = t + *f_p which is 3+2 -> f=5;
the variable pointed by f_p is set to t so x=3, returns f so it returns 5
this returned value is assigned to the t of the fun(5,f_p)(the first call to fun), f is f = t + *f_p which is 5+3 -> f=8;
the variable pointed by f_p is set to t so x=5, returns f so it returns 8, which is what the printf prints
Another answer revealed this to calculate the fibonacci numbers using a useful technique for returning an extra value. I've rewritten the code in what I think is a much more understandable and maintainable manner. Hope this prevents people thinking you need to write terrible code to do something like this
#include <stdio.h>
int fib(int n) {
// This is used to return the previous fib value
// i.e. fib(n - 1)
int prevValRet;
return fibRec(n, &prevValRet);
}
// *prevValRet contains fib(n-2)
int fibRec(int n, int *prevValRet) {
// Termination case
if (n <= 1) {
// return fib(0) and fib(1) as 1
*prevValRet = 1;
return 1;
}
// Calculate fib(n-1)
int prevVal = fibRec(n - 1, prevValRet);
// Calculate fib(n) = fib(n-1) + fib(n-2)
int thisVal = prevVal + *prevValRet;
// Return fib(n-1) and fib(n)
*prevValRet = prevVal;
return thisVal;
}
int main() {
printf("%d\n", fib(5));
return 0;
}
As these things go, it's technically straightforward, but...stupid, in the sense that nobody should do things like this. It's a bad use of recursion and badly-written recursion, given the side effects.
The original call of fun(5, &x) isn't going to trip the condition. So, it'll recurse four times (5-1, 4-1, 3-1, 2-1). That's your base condition, which has the effect of setting the pointed-to location (the original x) to 1 and returning 1.
Then we unroll the four calls, each time adding the returned value to the thing at the pointer and changing the thing at the pointer to be that sum.
In simple English, you're doubling one three times.
Edit: As pointed out, I misread the code as assigning f to *f_p rather than t. That makes it a Fibonacci counter.
What em trying to do is pass the array to a function which will add all the array elements and return the output. Please help me. i dont know what i am doing wrong in this :/
#include <stdio.h>
#define MAX 5
int arraySum(int *dArr,int lim);
int main()
{
int array[MAX] = {9,7,4,2,10};
printf("%d", arraySum(array, MAX));
return 0;
}
int arraySum(int *dArr,int lim)
{
int Ans;
if(lim>0)
Ans = dArr[lim] + arraySum(*dArr, lim--);
return Ans;
}
There are several problems with your code:
You're accessing array[MAX], which is undefined behaviour.
Your function returns the uninitialized Ans when lim is zero.
The first argument to arraySum in the recursive call is wrong.
The use of lim-- is wrong.
Since this looks like homework, I'll let you figure out how to fix these problems. If this isn't homework, you might want to consider whether recursion is the right tool for the job.
You run into undefined behavior on dArr[lim], because lim is 5 and the array has elements 0...4.
You also get undefined behavior when lim==0, because you return an un-initialized Ans. When you declare it, initialize it to dArr[0].
After you fix this, you'll want to pass dArr itself further in the recursion, as dArr only returns an int.
Remember that computers treat 0 as the first number, so your array will number from element[0] to element[4]. your code starts from five and counts down to one, which means elements[5] in this case will return garbage, because the index does not exist. pass Lim - 1 into the function or manually changed the value in your function.
ArraySum(Array, MAX - 1);
OR
ArraySum(//....)
{
lim--;
//code here....
}
EDIT: you also need to initialize ans to some value, so if an array of zero elements is passed the function wont return an uninitialized variable.
int arraySum(int *dArr,int lim)
{
int Ans;
if(lim>=0) // note the change here
Ans = dArr[lim] + arraySum(dArr, --lim); // note the --lim change here
return Ans;
}
You should invoke this with lim as 4 and not 5. Because the array has 5 integers starting from index 0 to index 4. 5th index is out of bounds.
--lim instead of lim-- because lim-- is post decrement. That means the value is first passed and then decremented. Hence everytime your arraySum function gets the value as 4 instead of 3, 2, 1 and 0 (as per your expectation). --lim is pre-decrement.
Change MAX to 4 and change the if(lim>0) condition as if(lim>=0)
This will make your recursion to add as dArr[4]+dArr[3]+dArr[2]+dArr[1]+dArr[0] i.e. all 5 elements of the array.
EDIT: Corrected program:
int main()
{
int array[MAX] = {9,7,4,2,10};
printf("%d", arraySum(array, MAX-1));
return 0;
}
int Ans = 0;
int arraySum(int *dArr,int lim)
{
if(lim>=0){
Ans = dArr[lim] + arraySum(dArr, lim-1);
}
return Ans;
}
#include <stdio.h>
int main(){
int a[4];
int b[4],i;
a[0] = 4;
a[1] = 3;
a[2] = 2;
a[3] = 1;
memcpy(&b, &a, sizeof(a));
for (i = 0; i < 4; i++){
printf("b[%d]:%d",i,b[i]);
}
printf("%d",sizeof(b));
}
ANS:
b[0]:4b[1]:3b[2]:2b[3]:116
Exited: ExitFailure 2
I'm getting the correct answers. But getting a exception as Exited: ExitFailure 2.
Is this way of copying the array datas using memcpy is wrong?
Try adding a return 0; at the end of main().
Omitting the return value is probably causing the function to return stack garbage. (that's not 0)
The test app/script is therefore complaining of failure when it sees a non-zero return value.
Prior to C99, omitting the return statement is technically undefined behavior. Starting from C99, it will default to 0 if it is omitted.
More details here: Why main does not return 0 here?
Correction:
Not explicitly returning 0 (return 0;) leads to undefined behaviour prior to C99.
However, since a particular register is usually used for storing a return value (for example eax in x86) from a function, the value in that register is returned.
It just happen to be that printf("%d",sizeof(b)); is storing the size of the char array in the same register that is used for returning a value from a function.
Because of this, the returned value is 2.
Original answer:
Since you do not state return 0; at the end of main, the last printf call is interpreted as the return value of main.
sizeof(b) returns 16 which is 2 characters long, thus the program returns 2 as exit code.
There is problem in your memcpy statement.
1) You should pass pointer to your array in stead you are passing pointer to pointer of
your array.
2) You should pass size of your array, sizeof(a) will return only size of int so u have to
multiply it with max index of array.
You have to do little modification in your code as given below,
memcpy(b, a, sizeof(a) * 4);