If you forget to put the terminating zero to the end of the string, then it will depend on the current context what will be there after the desired characters.
Your cycle transfers every character of the string, but doesn't transfer the terminating zero, that has to be done with a separate instruction. |
I partially understood. What do you mean by the current context.? What is the current context in this program. Sorry for asking too many questions. Just want to get this clear so that I dont repeat such mistakes.
|
The local variables are stored on the stack. And they are not initialized automatically. So their content will depend on what was on the stack earlier. For example, if you add another puts("Hello") into your program, the content of the stack might be different afterwards.
|
So str2 details are stored into a stack which already has some values in it.?. That's why the junk values are produced.?
|
So if I give str2="" initially. Can I overcome this problem.?
|
This goes back to the beginning of the thread. Out of curiousity, I ran a quick test:
Code:
#include <stdio.h> If I change the 2nd loop parameter to "i=0" then---as predicted by others---nothing happens. But, the compiler does not complain. SO....of what use is the "incorrect" construct? And--if it has no purpose, why does the compiler allow it |
Initialization with "" means putting zero into the first byte (as in str2[0]= '\0'). It doesn't mean that the k-th character will be zero.
PS: To tell the truth, I don't see why you keep bargaining; is it problematic to write a single statement: str2[k]= '\0'; ? |
> SO....of what use is the "incorrect" construct? And--if it has no purpose, why does the compiler allow it
The syntax of for is: Code:
for (expression; expression; expression) statement |
Quote:
Anyways thanks for your help. |
Thanks!!
My hangup was that the 2nd expression is supposed to be a TEST and not an assignment. So the compiler is saying (with no warnings turned on): "That statement is not illegal, but your loop won't work.".....? |
It doesn't prove anything: program-errors aren't bound to show themselves at the very first test.
If you want to be sure, do sg like this: Code:
char str2[80]; |
This is the code I was talking about.
Code:
int main() Code:
./a.out |
I've just checked with gcc; I was wrong, initialization with "" does fill the whole str1 with zeroes (with five machine instructions).
Still, putting an 's1[k]='\0'; after the cycle would be a good idea (two machine instruction). |
Quote:
Secondly, you are allocation the array str[10] statically, which means 10 garbage values. Plus you are not appending with '\0', hence you should expect what the output you are getting. In comparison to the output what you get, check the one what I am getting with the same piece of code. Yours: Code:
enter de string Code:
enter de string Lastly, please make it a habit of using proper indentation of your code. |
All times are GMT -5. The time now is 11:52 PM. |