C pointers!

Started by
5 comments, last by tdk_ratboy 20 years, 5 months ago
Hello, was wondering on the use of strcpy function. Am trying to use it with a TCHAR and a TCHAR *. It compiles and runs with an error that says it is accessing memory at location 0x000000. If anyone knows how I can copy the contents of the pointer to the array I would appreciate it. Thanx in advance!
Advertisement
You need to allocate the space that you are copying into using strcpy. For example, this will not work:

char *ptr;
strcpy(ptr, "Hello World");

because ''ptr'' has not been initialized to point to anything. You could do the following:

char *ptr, buffer[128];
ptr = &buffer[0];
strcpy(ptr, "Hello World");

because ''ptr'' now points to valid storage - the local variable ''buffer''.

The toughest thing to understand about pointers is that, by default, they don''t point to ANYTHING valid. You have to assign them to point to some valid storage. That valid storage might be other variables or memory that you allocate using either malloc or new.

using the string class is easier




--{You fight like a dairy farmer!}

--{You fight like a dairy farmer!}

Good call OldGuy, and ptr = buffer also achieves ptr = &buffer[0].

Wizza Wuzza?
Your''re right, Chris. Guess I''m showing old habits and age - old C compilers didn''t let you assign a pointer to an array...
that error normally means that your trying to dereference a NULL ponter, the pointer == 0.
quote:Original post by Greatwolf
using the string class is easier




--{You fight like a dairy farmer!}


True, if you are using C++. The topic however is ''C pointers!'' which probably means the person is programming in C and not C++, thus not having the STL available.
-----------------------------Final Frontier Trader

This topic is closed to new replies.

Advertisement