Re: [Dev-C++] strcpy x pointer array
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-03-06 23:44:34
|
char *vect[100] means that you have an array of 100 character pointers.
the first assignment assigns the address of a string, i.e. a character
pointer to the 4th element of your array. That's ok.
Your line 'y' on the other hand tries to copy data to the pointer already
stored in vect[3].
If you run without line x, vect[3] will point to random address and the
copy will most probably fail misserably.
If you run with line x, vect[3] will point to a constant, i.e.
write-protected (for most environments at least), text string that your
compiler has created. The strcpy() call will then fail misserably when it
tries to overwrite the write-protected memory where the first "text"
string is stored.
You might do:
vect[3] =3D strdup("text");
...
free(vect[3]);
strdup() will first allocate a block of memory large enough for the
string. Then it will copy "text" to the new memory block. Then it will set
the character pointer vect[3] to point at the newly allocated memory.
However, to avoid memory leaks, you must then release the memory that
strdup() allocated, i..e calling free() on it.
/Per W
On Thu, 6 Mar 2003, Andr=E9 Mac=E1rio Barros wrote:
> 1. Please consider the following piece of code
>
> #include <stdio.h>
> #include <string.h>
> ...
> int main()
> {
> char *vect[100];
>
> ...
> /* line x */ vect[3]=3D"text";
> ...
> /* line y */ strcpy(vect[3], "text");
> ...
> }
> ...
>
> 2. Both commands in lines x and y don=B4t gererate any compilation errors=
;
>
> 3. The command in line x works fine;
>
> 4. Why the command in line y generates an execution error interrupting th=
e
> execution of
> the program?
>
> Regards
> Andre
>
>
>
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by: Etnus, makers of TotalView, The debugg=
er
> for complex code. Debugging C/C++ programs can leave you feeling lost and
> disoriented. TotalView can help you find your way. Available on major UNI=
X
> and Linux platforms. Try it free. www.etnus.com
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|