New course! Every coder should learn Generative AI!
Try a free lesson+ 1
Why there is no output?!
This question was in a C challenge What is the output of this code? char p[20]; char *s = "string"; int length = strlen(s); for (int i = 0; i < length; i++) p[i] = s[length - i]; printf("%s", p); The answer was No output.. can anyone tell me why??
9 Answers
+ 5
The length of string "string" is equal to 6
Every string in C ends with null-character ('\0'). It is implicit and it is appended by C for you.
The 6th character of "string" is null-character:
0 1 2 3 4 5 6
's' 't' 'r' 'i' 'n' 'g' '\0'
The first character you are copying in the loop is character with index 6, so the first character of p will be '\0'.
After executing of the for loop array p will contain the following chracters:
p = {'\0' , 'g', 'n', 'i', 'r', 't'};
So, p is an empty string (as first character is null-character) and you will get no output when you print the empty string. (The rest of characters in p will be ignored cause the end of a string is null character).
+ 5
What AJ said is true , and if you wonder why you get no output it's because the off-by-one error copies the null-byte at end of the string (because string[6] is '\0') and places it at the beginning of p.
because p[0] is a null byte, printf thinks it reached the end of the string so it prints nothing.
+ 4
Mostafa Ehab You should write
s[length - i - 1]
Because index start from 0 show when you write [length - i] then you will get index 6 (6 - 0) on i = 0 which is wrong but when you write [length - i - 1] you get index 5 on i = 0
Finally it will look like this:
p[0] = s[length - 0 - 1] = s[6 - 0 - 1] = s[5] = g
p[1] = s[length - 1 - 1] = s[6 - 1 - 1] = s[4] = n
p[2] = s[length - 2 - 1] = s[6 - 2 - 1] = s[3] = i
p[3] = s[length - 3 - 1] = s[6 - 3 - 1] = s[2] = r
p[4] = s[length - 4 - 1] = s[6 - 4 - 1] = s[1] = t
p[5] = s[length - 5 - 1] = s[6 - 5 - 1] = s[0] = s
+ 4
Mostafa Ehab on index 6, program is giving exception and displaying no output.
In Java we get ArrayIndexOutOfBound.
But in C I am not aware much so I won't be able to tell
+ 4
andriy kan
You mean to type: p = { '\0', 'g', 'n', 'i', 'r', 't' }, no?
My thinking is: i stops at 5 which is < length (length is 6) and i begins at 0. That would mean length - i start from 6 and end at 1 to skip first character at position 0?
+ 3
Mostafa Ehab As I told you index start from 0 so when you reverse the string then index will look like this
g, n, i, r, t, s
5, 4, 3, 2, 1, 0
+ 2
Gen2oo
Yes, you are absolutely correct, p will be
{'\0', 'g', 'n', 'i', 'r', 't'}
's' will not be copied.
I just tried to show the main idea and didn't look at the code when was typing the answer.
+ 1
AJ #Infinity Love ok but why it’s not “nirts”
+ 1
Also...'p' is not yet a string... it's just an array of characters...you need to append a NULL ('\0') to the end of it to make it a string.