#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);
Related
In C
int n=100;
printf("%d", (int)(sqrt((double)n)));
When I use this code it prints the correct answer (10).
But following code always prints 0
int n;
int max = (int)(sqrt((double)n));
printf("%d", max);
Why are the answers are different ?
int n=100;
printf("%d", (int)(sqrt((double)n)));
In this case, the value of n is known i.e, 100. So sqrt((double)n) returns the correct value.
int n;
int max = (int)(sqrt((double)n));
printf("%d", max);
Here, the variable n is uninitialized. The variable could be holding an indeterminate value depending upon whether it is declared locally (inside a block, in which case the value of n would be a junk value) or globally (outside a block, in which case the value of n would be zero). Always initialize your variables to avoid such errors.
I tried to compare int variable with the function in two ways:
storing the int function return value in a variable then comparing with another
in value.
Directly comparing the int variable and the function call.
Here I got the answer for the first one but not for the second one.
Why does this happen?
My code:
#include < stdio.h >
int count = 0;
int countDigits(int);
int main() {
int i;
int result = countDigits(435);
for (i = 0; i < result; i++) {
printf("id %d\n", 3);
}
for (i = 0; i < countDigits(435); i++) {
printf("i =%d\n", i);
}
}
int countDigits(int n) {
if (n == 0) {
return count;
} else {
countDigits(n / 10);
count++;
}
}
We can.
It's just that your function has a logical error. Debug it, and you will be fine.
Enabling compiler warnings would have helped you. For example with GCC and Wall flag, you get:
prog.c: In function 'countDigits':
prog.c:32:1: warning: control reaches end of non-void
function [-Wreturn-type]
}
^
Tip: Think of what your function does if n us different than zero.
count is a global variable.
The function countDigits(n) adds the number of decimal digits in n to count and
If n is zero it returns 1.
If n is non-zero the return value is undefined.
Since countDigits(435) has an undefined value, anything can happen and no further analysis is necessary.
Let's assume that this obvious error is corrected by inserting return count; after count++;. In this case, the function returns the incremented count.
So we have this nice sequence:
Set result to countDigits(435).
countDigits(435) adds 3 to count and returns 3.
Set i to 0 and compare to countDigits(435).
countDigits(435) adds 3 to count and returns 6. 0 is less than 6, so the for loop continues.
Now i is 1, and we compare it to countDigits(435).
countDigits(435) adds 3 to count and returns 9. 1 is less than 9, so the for loop continues.
Now i is 2, and we compare it to countDigits(435).
countDigits(435) adds 3 to count and returns 12. 2 is less than 12, so the for loop continues.
... And so on.
Morality:
Beware of side effects. Never use and modify global variables unless you have a good reason to.
When you must use side effects, keep them prominent in your mind.
It is possible to compare a variable directly with the output of a function. However, your function countDigits has several problems.
Not all code paths return a value - you're missing a return statement in the else block. This alone makes the output of the function undefined.
It's not algorithmically correct. Have you tried debugging it? Just start with printing the output for different inputs and you'll see.
Modifying and returning a global variable count inside that function is a really bad practice - it should be local to the function. When it's global, every call to the function modifies a [possibly] already modified variable.
Others have already addressed the problem here with globals, so I will not go into details about that. Instead, here is a solution without globals:
int countDigits(int n) {
int count = 0;
while(n>0) {
n/=10;
count++;
}
return count;
}
I guess you could be philosophical about whether 0 has 0 or 1 digit, but your code implied that you wanted it to be 0. If you want it to be 1 instead, just change the first row to int count = 1.
I wrote some code to count the bits in a word. When I printf() the count it prints 32 as expected but when I stuck the same code in a function and printed the return value it gives me some crazy large number.
I then copy/pasted the code back into main() printed the count and printed the return value of my function at the same time and hey both gave me 32 but if I then comment out the code in main() my function again prints the large number.
Anyone have an idea about why this is happening?
#include <stdio.h>
int wordlength();
int main() {
printf("%d", wordlength()); // prints 4195424 but
// if I uncomment the code below
// it then prints 32 like I want
// int count;
// unsigned int n = ~0;
//
// while( n != 0) {
// n = n >> 1;
// count++;
// }
// printf("\n%d", count); // prints 32 as expected
return 0;
}
int wordlength() {
int count;
unsigned int n = ~0;
while( n != 0) {
n = n >> 1;
count++;
}
return count;
}
In your wordlength() function, count is an automatic local scope variable and is not initialized explicitly. So, the initial value is indeterminate.
To quote C11 standard, chapter §6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. [...]
You're readily applying post-increment onto it. It invokes undefined behavior.
Related, annex §J.2, reasons for undefined behavior,
The value of an object with automatic storage duration is used while it is
indeterminate.
So, your program exhibits UB and not guaranteed to produce any valid result, at all.
Solution: Initialize count to 0.
FWIW, regarding the comment
// if I uncomment the code below
// it then prints 32 like I want
is also a result of UB.
You have to initialize count to 0 or something, or it will have undefined value.
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].
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;
}