useing char pointer or a char array .. i'm a little confused.

Started by
3 comments, last by xyuri 18 years, 1 month ago
I need to rewrite some string handling functions for an assignment (using ONLY POINTERS) which has left me needing to work with chars a lot! Ok, well, basically, I wrote some test code using a char* variable, and passing it to strcpy to put a value into it ... which didnt work, but it works when i pass it a char array. why is this? i thought these were basically the same thing?
__________Michael Dawson"IRC is just multiplayer notepad." - Reverend
Advertisement
Without seeing the code, I wouldn't know what you did wrong. With strcpy, you need to make sure the original array is null terminated and the new array is strlen(original + 1) to account for the null character.
Are you saying you did something like this:
char* s = "Hello World!";char* str = "hi";strcpy(s, str);


So you were trying to copy into a string literal? I don't know for sure, but I've had a couple of problems like this. I think that string literals are write protected or the memory that they are stored in inside the executable is, or something of the sort.
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
You should post some code up to make things a little clearer.

My guess is that you haven't assigned any memory for you char * variable to point to.

i.e you have code like:

char stringSource[] = "Hello";
char *pString;

and then use it as a parameter in the strcpy function like:

strcpy(pString, stringSource);

This doesn't work because pString doesn't actually point to any memory yet and so when you use the function it may cause your program to crash. You will need to do something like:

#define MAXSTRING 10
pString = malloc(MAXSTRING);

so that pString actually points to some memory and therefore allow you to copy upto a maximum of 10 characters using the above code.

One thing to be aware of is that you have to make sure that you have allocated enough memory to hold the string you are copying from. So if you have code like:

char stringSource[] = "Hello wonderful world";
and then try to copy this string to pString then your program could behave erratically.

The last point in your post is that it works with char arrays. This is because the compiler has already allocated memory for your array and so you have space to copy into.
How about them apples?
Thank you popcorn, you have been most helpful! as quoted from cpluspluscom:
Quote:Copies the content pointed by src to dest stopping after the terminating null-character is copied.
dest should have enough memory space allocated to contain src string.

It totally slipped my mind that when you simply do "chat* c;" it isnt pointing to anything at all :)

Thanks.
__________Michael Dawson"IRC is just multiplayer notepad." - Reverend

This topic is closed to new replies.

Advertisement