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

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.

Related

Pointer issue while running a pointer program [closed]

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.

How to explain the output of this program 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've been working on this problem:
#include<stdio.h>
int main()
{
printf("%c", "abcdefgh"[4]);
return 0;
}
This gives e as the output, however I couldn't understand that how an array named "abcdefgh" with 4 elements is getting printed.
In nutshell, please tell me how this program works.
The string "abcdefgh" doesn't have 4 elements. It's an array with 9 elements (the characters plus the null terminator, and square brackets are the array subscript operator.
So "abcdefgh"[4] is getting the element at index 4 from "abcdefgh" which is 'e'.
In C, a string is sequence of character terminated by null character (\0).
When you declaring a string:
"abcdefgh"
it's actually:
char array[9] = "abcdefgh";
and you are accessing 5th character from the array, since array is 0-based data-structure.
you are actually doing:
printf("%c",array[4]);
therefore, it points to 5-th character in array;
a b c d e f g h
0 1 2 3 4 5 6 7
A string literal like "abcdefgh" is an array expression - its type is "9-element array of char" (8 characters plus the string terminator). The subscript operator works on it like any other array expression, so "abcdefgh"[4]" evaluates to the 5th element of the string, which is the character 'e'.

Not understanding weird behaviours of printf() [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 4 years ago.
Improve this question
I found a question asking for output of the following statement :
printf("%d"+1,123);
The answer given was d, It's explanation was : Since "%d" is a string, +1 here means d.
123 just gets ignored.
My first question is : why 123 gets ignored?
I also ran the following statement
printf("%d"+2,123);
It printed nothing. The code runs but without errors.
My second question is : why did the code compiled without errors?
Third time, I did following:
printf("%d"+0,123);
Output was 123.
So I am getting real confused here. If +1 printed d, then shouldn't +0 print %?
Imagine a string:
char str[] = "%d";
Now we know that:
str[0] == '%'
str[1] == 'd'
str[2] == '\0' = 0x00
str+2 == &str[2] == the address of the byte 0x00 inside the str string == ""
printf("%d", 123); is the same as printf(str, 123)
printf("%d" + 2, 123); if the same as printf("", 123); and it will print "", ie. nothing
A character point with an addition lead to a character point.
printf is just a function
So it takes a variety of parameter - varags
"%d"+1 Will be a string just dn it
"%d"+2 - will be the null byte - nothing
"%d"+0 - Will be %d - hence expected output - see the manual page
Answer to your first question:
123 gets ignored because while writing printf("%d"+1,123), +1 places the pointer at index 1 of %d i.e d. Since, to print 123 we need the pointer to be at % and access %d and not just d. Hence, only d gets printed out in this case.
Answer to your second question
It compiled without error because printf() is just a function and it takes various arguments. For more details about printf() you can visit this link
And in the third case i.e printf("%d"+0,123), the output is 123 because here the pointer's position is at 0 i.e at % and we have access to %d. Hence, we're getting 123 as output.
hope this will help you.

Why does it show the output as zero and not the garbage value if the variables have not been initialized? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Here is a program in C language that simply displays variables that have not been initialized,
#include <stdio.h>
int main()
{
int a, b;
printf("%d%d",a,b);
return 0;
}
Output:
00
I have started learning c programming 20 minutes ago for the first time in my life, can you tell me why does it show the output as 00, now since we're supposed to initialize out variables with 0 in most cases to avoid seeing the garbage value in their place so I just wanted to know why does it happen ? Why don't we get a garbage value instead and not the plain '0' which has its own ASCII value?
int x = 0;
printf("%d", x); // -> 0
shows the value of x as an integer in memory. However, uninitialized variables cannot be trusted to have a value of zero every time. See What happens to a declared, uninitialized variable in C? Does it have a value?
If you want the character representation of that integer, use
int x = 99;
printf("%c", x); // -> c
instead. It will give the ASCII representation.
int x = 99; means 'c')
variable not assigned doesn't mean that it has no value, it just means that the value is not defined (or known if your prefer). But be careful, reading a variable that has never been initialised is undefined behaviour.
By default C does not give a value to uninitialized variables, you have to tell it what to store in each variable. If you do attempt to use these variables without giving them a value, the output will be unpredictable.
For example when I ran this on my pc I go the value: 41944324050944
Do not do this. If you do your program will throw unexpected results when you run it later. See this.
The proper way you would do this is to define a and b like this:
int a = 0;
int b = 0;
In the case of defining static storage the default value would be 0 (always) see this web page for more information.
This program will return 00 as expected:
#include <stdio.h>
int main()
{
static int a, b;
printf("%d%d",a,b);
return 0;
}
even-though a and b are not assigned a value the use static storage and therefore have a value 0.
Also if you want ASCII characters printed use %c instead of %d. See here. Also note that 00 in ASCII is null see here for printing null variables.

I am finding difficulties to solve an expression [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 8 years ago.
Improve this question
I am finding difficulties to solve an expression please help me to do so.
Declare four variables of type char. Initialize one variable to ‘z’. Initialize the other variables to the ASCII integer value for ‘z’, the ASCII octal value for ‘z’, and
the ASCII hexadecimal value for ‘z’.
Just declare a char variable and assign the value. To assign hex prefix with 0x, for octal use 0 and for decimal just write the number with no prefix.
The decimal ascii value of 'z' is 122.
#include <stdio.h>
int main() {
char a = 122;
char b = 0x7a;
char c = 0172;
char d = 'z';
putchar(a);
putchar(b);
putchar(c);
putchar(d);
}
All these char variables have the same value so four zs will be printed.

Resources