Quote:If I change char x to char *x and char y to char *y ,why compiler hit error?
This gets a little complicated for a beginner, but here goes ... I'll try to be gentle with you!
There are two "types" of memory that a C program uses:
Heap is a huge block of memory that is allocated to a variable when you specifically ask for it using the
function, and it is your responsibility to release it when you are finished using
- if you don't then you get a problem called a "memory leak" where you program just keeps grabbing more and more memory that it is no longer actually using. In extreme cases, this can cause you app or the system to crash.
Stack is a much, much smaller block of memory that is allocated to each
(think of an app as a thread, it's not really accurate, but it'll do for the moment). And when I say "much, much smaller" I'm serious: while a
might use all the physical memory in your computer plus all the spare space on your hard drive ad "virtual memory", a
is rarely larger than 1MB. It holds all the variables that are local to a function, plus all the "return addresses" that tell your app where to "go back to" when it returns from a function. Each item (generally 32 bits of data, so an integer, or four characters) occupies one "location" on the stack, in the same way that coins in a real stack do: you add them at the top, and you can only remove them from the top as well, because trying to take them from the middle is like getting overambitious at Jenga - it all falls over! :laugh:
When you call a function, the system puts the return address on the stack and then adds enough space for all the local variables: in your case 40 bytes for the two arrays (though in practice, it'll probably allocate 32 bytes for the first on, and 12 for the second just so they start and end on a word boundary - makes it easier is all).
You then call
and it does the same thing: stacks the return address allocates space for the two pointer parameters (though in practice those will probably now be memory at all, but use registers within the processor).
then copies characters from one pointer to the other - overwriting whatever was there to start with. And since this is a stack, if the destination doesn't have enough space, it doesn't notice or even care and overwrites whatever it can find - in this case the return address which is going to tell the system where to resume executing
when the function ends.
It gets to the end of the function, takes the return address you just overwrote back off the stack, and tried to execute code there - and since it's no longer a valid program location, you get an error and your app crashes.
Does that make sense? It's difficult to explain without pictures ... :laugh: