-
Pointers and Strings
I've been struggling quite a bit to get some theory and code working together. You see, I was working on some code to use a char* as a string, and I get this error from GCC that I'm trying to go from char to integer or something without a case. Anyways, I'm not sure what I'm doing wrong or what I need to do to fix this code. Here is the faulty code:
Code:
char *test_ptr;
char string[] = "This is a string";
test_ptr = string;
*test_ptr = "Th";
What's wrong with this code? Why isn't it working? What do I need to do to get it working? Thanks!
-
You are trying to do an illegal assignment. What you have is a bunch of char's. What you are trying to assign to one of those char's is char[3]. Take a look at what you have.
*test_ptr = "Th";
What happens if you ouput *test_ptr? You will get 'T'. Because that is the single character stored there. Now you are trying to replace the character 'T' with 'T', 'h', '\0'. Remember when you use " " you automatically get the null terminator. You use single quotes to specify characters. So try changing that to...
*test_ptr = 'T';
If you still want the h, you'll need to increment the pointer and assign 'h' to the next value. Good luck.
-
okay, I wanted to put the whole string into the pointer at one shot. so, I changed this code to:
this is perfectly legal and correct, right? now test_ptr points to that string, correct? thanks.
-
okay, i was just a little unsure and now i'm having some memory problems because windows shuts down an "illegal operation" and i think i'm just impeding somewhere in memory i shouldn't. i'll try to work that out.