View Full Version : Character Pointer Const? - C++
magicyte
11-26-2008, 09:21 PM
I want to be able to copy some characters into a string from a parameter variable in C++. Here is code I made:
char name[];
void setName(const char *n) {
name = *n;
}
Syntax:
setName("Jimbo");
I know that the two types of variables are incompatible. How can I do this!? You know, copy a string into another string through parameters. Thanks in advance!!
-magicyte
#include <string.h>
char *name;
void setName(const char *n)
{
name = strcpy(malloc(strlen(n) + 1), n);
}
magicyte
11-26-2008, 11:09 PM
Thank you! I was, just a minute ago (TRUE FACT), thinking about strcpy and if you needed string.h to use it. And voula! :)
Is it possible to do this without strcpy? Doubt so, but I would like to understand it.
-magicyte
Well, yes, if you reimplement strcpy():
char *strcpy(char *dest, const char *src)
{
int i;
for (i = 0; src[i] != '\0'; ++i)
dest[i] = src[i];
return dest;
}Most C functions are very naïve. This means that they're easy to reimplement (but horrible to work with). Note that the GNU implementation of this is considerably more complex, for efficiency reasons.
magicyte
11-27-2008, 05:54 PM
Thanks for the strcpy code! Now, when I compiled the first code w/ string.h and malloc, my compiler said 'malloc' was undeclared. I came up with this code:
char *name;
void setName(char *n) {
name = n;
}
Is this good or bad? I use it since the 'malloc' didn't work. Could you also describe what malloc does? Just from the name, I'm guessing it allocates memory...
I am also having trouble with this:
char *name; // already has value from setName()
char getName(void) const {
return *name;
}
name = getName();
Also tried this:
char *name; // already has value from setName()
char getName(void) const {
return name;
}
name = getName();
and this:
char *name; // already has value from setName()
char *getName(void) const {
return *name;
}
name = getName();
Even this!!:
char *name; // already has value from setName()
char *getName(void) const {
return name;
}
name = getName();
The last code I gave, compiler compiles, and a big bomb goes off in the DOS console. What do I do? They don't work. My compiler flags an error when I try to compile it.
-magicyte
magicyte
11-27-2008, 06:53 PM
Oh. Nevermind. The last code DOES work. I was doing this:
#include "stdio.h"
#include "conio.h"
#include "game.h" // has code
int main(void) {
Warrior mario;
mario.setName("Mario");
printf("%s is the warrior of Strraughtnauten"); // no reference to %s!! silly me
getch();
return 0;
}
Ha! Imagine that... :D
-magicyte
malloc() is defined in stdlib.h. It allocates the number of bytes provided and returns a pointer to the allocated memory, or NULL if the memory could not be allocated. Memory allocated by the likes of malloc() must be freed with free(). There are also helpers for common cases: see the man page.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.