Pointer issue while running a pointer program [closed] - c

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I am a new C language learner. I am currently learning about pointers and got confused while reading this code. At line three, p was defined as a pointer variable, but what exactly happened at line 4? Was a's char array stored in p? Also, at line seven, doesn't i++ mean i = i + i? In this case, why isn't the output 13 instead of 12?
Thank you
#include <stdio.h>
int main()
{
int a[]={10, 20, 30, 40, 50};
int *p; // Line 3
p=a; // Line 4
int i=12;
printf("%d,%d\n",i++,*p); // Line 7
printf("%d,%d\n",i++,*(p+1));
printf("%d,%d\n",i++,*(p+2));
return 0;
}

Regarding p=a, in most contexts an array decays to a pointer to its first element. This means it's equivalent to p=&a[0]. So while p doesn't contain the entire array a, it points to the first member of the array, and can be indexed to access subsequent members.
Regarding i++, the postfix increment operator evaluates to the current value of its operand, and the operand is incremented as a side effect.

What happens when the array a is assigned to the pointer p is that the address of a (which equals the address of a:s first element) is assigned to p. Here is a picture which illustrates the situation at line five:
The expression i++ does indeed increment i by one but its value is i before the increment. That's why the first printed value is 12. Compare this to ++i which also increments i by one but its value is the incremented value of i. In general it's a good idea to avoid side effects in expressions; the print statements are better written as
for (int j = 0; j < 3; j++) {
printf("%d,%d\n", i + j, *(p + j));
}

The output is:
12,10
13,20
14,30
When the first printf() is called:
i is 12, printed and then incremented (new value 13).
p point to array a (first element) so de-referencing the pointer gives 10.
When second printf() is called:
i is 13, printed and then incremented (new value 14).
p point to array a (first element), you add 1 so it point to the second element in a so de-referencing the pointer gives 20.
When third printf() is called:
i is 14, printed and then incremented (new value 15).
p point to array a (first element), you add 2 so it point to the third element in a so de-referencing the pointer gives 30.

Related

Reproduce values from an original array after substitution of each element with the mean value of its neighbours in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have substituted the values in an array with the values of the arithmetic mean of its neighbours in C:
int main(void) {
int tab[5] = {1,2,4,6,8};
for (int i = 1; i<4; i++) {
tab[i] = (tab[i-1]+tab[i+1])/2;
}
return 0;
}
I have excluded the first and the last element. Then, I want to reproduce the orginal values in the modified array. I have tried:
for (int i = 3; i>=1; i--) {
tab[i-1] = 2*tab[i] - tab[i+1];
}
but it doesn't work. How to reproduce the original values? I want to modify the original list in order to avoid the memory usage for initialization of the new array.
You can't do that IN THIS CASE.
Also there are hidden mistake in your code (explained at bottom)
look at the modified array in your case
arr[0] = 1 //unmodified in loop
arr[1] = 2 //(5/2 = 2) in int data type
arr[2] = 4 //(arr[1]+6)/2 = (2+6)/2 = 4
arr[3] = 6 //(arr[2]+8)/2 = (4+8)/2 = 6
arr[4] = 8 //unmodified
since, its a specific case where the modified array is same, so some of the mistakes would be hidden.
but what happens when your second loop has i=1
arr[i-1]=2*arr[i] - arr[i+1]
arr[0]=2*arr[1] - arr[2]
taking values from above
arr[0] = 0 // which is different from original arr[0]
If you want to just examine this use float instead of int as data type of array and see what happens.
also try putting an even value in the first element while using the int data type.
Now, the mistakes
you said you want to replace elements with avg of their neighbours. but (not in this special case where original elements are retained) what happens is the loop works correctly only 1st time and from 2nd run it is taking a value tab[i-1] which you modified in the previous loop run.
same is the case of your second de-modification loop, from 2nd run onwards, it takes a value tab[i+1] that you modified in previous run.
even if everything else works,
do you realize that in second loop, you are assigning original values from 2nd to 0th positions instead of their original 3rd to 1st.

how does array[1-'a'] work in c programming? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm working on a program to find the anagram to two strings in c. But I end up in a statement
array[1-'a']++;
and I don't quite know the working of that statement.
Anyone out there help me..!
ASCII value of 'a' is 97. 1 - 97 is -96. array[-96] is equivalent to *(array - 96). If array - 96 is a valid address then array[1-'a']++; will give the value at address array - 96 incremented by 1, otherwise dereferencing it will invoke undefined behavior.
'a' is a character constant and it is an integer which is the character code of a (97 if ASCII code is used).
array[1-'a'] is equivalent to *((array)+(1-'a')), which is 1-'a' element after ('a'-1 elements before) the element pointed at by array. ++ is incrementing, which is equivalent to adding 1. array[1-'a']++ is postfix increment, so this expression will be evaluated to the value of array[1-'a'] before incrementing.
An example of possible usage:
#include <stdio.h>
#include <limits.h>
int main(void) {
int data[SCHAR_MAX] = {0};
int* array = &data['a'];
printf("%d\n", data[1]); /* 0 will be printed */
array[1-'a']++;
printf("%d\n", data[1]); /* 1 will be printed */
return 0;
}
array[1-'a']++;
a is ASCII 97.
1 - 97 is -96
array[-96], if a valid address, is 96 elements before the base address of array
++ increments its operand, or array[-96].
This code, however, is highly dubious in its correctness.

Does setting a variable equal to a decrementing variable change all values of that variable? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
If you had the following code:
j=3; // Line 1
i=6; // Line 2
i+=5; // Line 3
j=i--; // Line 4
... to my knowledge, the value of j would become 6. If it was --i, it would be 5 etc.
But if I print out the value of i after line 4, I get 10 instead of 11 which is on line 3.
Why does this happen? Does this mean if I declared i to be a number and later on I go back the code and set another variable to i--, before most of my i's in the code, it changes the value of i globally?
In your code, see the following step-through.
j=3; //Line 1, j ==3
i=6; //Line 2, i == 6
i+=5; //Line 3, i == i + 5 == 11
j=i--; // line 4, j == 11, i == 10, after this line.
To elaborate, the x += y can be broken down as x = x + y, so that's it.
and regarding the post-decrement, the side-effect (decrement) will take place after the expression is evaluated. So, anyway, before the next statement, the value of i will get decremented.
To add some reference, from C11, chapter ยง6.5.2.4,
The result of the postfix ++ operator is the value of the operand. As a side effect, the
value of the operand object is incremented (that is, the value 1 of the appropriate type is
added to it).[....]
and
The postfix -- operator is analogous to the postfix ++ operator, except that the value of
the operand is decremented (that is, the value 1 of the appropriate type is subtracted from
it).
Note, a difference of a pre-decrement and post-decrement is visible only within the expression they are used. From the perspective of the next instruction using the variable, they both will give you the same result (effect).
First you make the value of i become 11, then you assign this value to j and then the decrement of i happens. The last line is equivalent to
j = i;
i -= 1;
If you did j = --i; then the last line would have been equivalent to
i -= 1;
j = i;
and j would have become 10.
The -- decrement operators are not the same as subtraction by one. They modify the lvalue on which they were used, so any time i-- is used, i will be modified.

Describing the following code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I've got a question regarding an assignment i've been given.
-There are two integeras, a and b, which has the value of -1 and 1 respectively.
What's the value of a and b after running the following code and WHY.
if(!++a)
b+=a++;
When i run this code i'm getting the values 1 and 1. I can not really figure out WHY though... Im getting quite confused over the if statement, could anyone explain this for a beginner trying to learn C?
Your code is equivalent to this one:
int a = -1;
int b = 1;
a += 1;
if (a == 0) {
b += a;
a += 1;
}
You should see why both variables end up as 1 here. Now try to figure out why these codes are equivalent.
if (!++a)
First of all, if (a) is identical to if (a != 0). Weird, but true. Zero means false, any other number means true.
Saying if (!a) inverts that meaning.
++a increments a and returns the new value. (Unlike a++, which increments a but returns the old value, not the new one.)
Putting all that together, this says "increment a and test whether the answer is zero". If a = -1, then this is indeed true.
Usually people would write if (...) {do stuff}, but if the "do stuff" part is only one statement, you can leave out the brackets. We've already established that the condition is true in this case, so the "b+=a++" line is run.
If we put some spaces on that, we have
b += (a++);
So, increment a again, but before that, add it's (old) value to b.
++a gives you the value after increment, so you get 0 which means false. The ! operator makes it true.
Then you basically have
b = b + a;
a++;
So b remains 1 and a gets another increment and ends up at 1 too.
The main concept here is the difference between a++ and ++a. If you use a++ you will first get the value of a and then the value is incremented whereas for ++a the value is first incremented and then returned.
Initially a= -1 when your code will enter if (!++a) and it is pre increment first increment of a will happen so a will become 0 and !0 is 1 and it will enter in the if block.
now b+=a++;
here a++ is post increment so you can devide this statement in two parts.
first b+=a; b+=0 so b will remain 1.
second a++; a will become 1.

How does this array program in C give the result 10? [duplicate]

This question already has answers here:
With arrays, why is it the case that a[5] == 5[a]?
(20 answers)
Closed 9 years ago.
I am using Ubuntu 12.04lts with the GCC compiler. This program gives the result 10. Could you anybody please describe why this program gives the result like this?
#include <stdio.h>
void main(void)
{
int arr[1] = {10};
printf("\n%d\n\n", 0[arr]);
}
arr[0] gets internally expanded to *(arr+0). Similarly 0[arr] gets expanded to *(0+arr) which points to the same thing. Hence you see 10.
In general for an array or a pointer a, a[b] always means *(a+b) where a is the starting address of the array or pointer and b is the offset. Thus, a[b] and b[a] are equivalent.
below line means arr is int type array and it has size 1 and it is initialized with 10 ie index 0 has 10
int arr[1] = {10};
then next line printf statement printing the value of arr at index 0.
printf("\n%d\n\n",0[arr]);

Resources