Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
#include <stdio.h>
#include <string.h>
main()
{
char name[]= "Alex"; 
strcpy(name, "Alexander"); /* This line */ 
}


What I have tried:

What is wrong with the strcpy line?????
Posted
Updated 27-Feb-17 10:32am
v2
Comments
[no name] 27-Feb-17 15:06pm    
If I were to pretend to be a mind reader and I were trying to read your mind, I would guess that you are looking at an overflow. http://www.cplusplus.com/reference/cstring/strcpy/
cvogt61457 27-Feb-17 15:08pm    
You didn't say what happened when this line runs.
Are we to guess what went wrong?

Note: name is a char[] with a length of 5. Try setting the length to 15.

This is your homework, not ours-so you should be more than capable of working this out just by reading your course notes. But...
When you initialise a string without specifying a length:
char name[]= "Alex";
the array is given exactly enough space to accomodate the string, in this case 5 characters (one for each letter plus a null terminator).
I you then use strcpy to copy a longer string into the array:
char name[]= "Alex"; 
strcpy(name, "Alexander");
it doesn't have enough space and you will either get an error (if you are lucky) or you will corrupt other memory.
 
Share this answer
 
Comments
CPallini 27-Feb-17 15:32pm    
5.
Your problem is that with C language, memory allocation and release is manual, you are the one that manage it. It is one of the pitfalls of C.
strcpy try to a string of 10 chars in a place of only 5 chars.
To see your program perform, use the debugger.
-----
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900