Pointers are really important in C and C++. I'd strongly advise that you make every attempt to understand them before you move on to other things. What don't you understand? Perhaps we can help.
Yeah I figured they'd be as anyone I know that codes in c++ had problems understanding them.
I understand why you would reference a variable, but why you would need its raw address to play with?
I got that
int apple = 25; //is a variable
int * apple_pointer = &apple; //the apple_pointer variable is now a pointer *. The & character converts from int to int * which gets the pointed variable's (apple) memory address.
Did I got that right?
What I don't understand is where this could be useful since I can work with normal variables fine.
and why would I do:
int orange = *apple_pointer;
when I can simply do:
int orange = apple;
string.h just provides more functions that manipulate character arrays via pointers. That is the definition of a string in C — an array of characters with a pointer.
I don't mind using char, but what I am concerned about is their datatype width. 0 to 255 characters max unsigned. It's really not enough if you have long text. I figured string would be like the 'text' datatype in SQL.
Isn't there any data type like this?
Now about the code:
Code: Select all
#include <stdio.h>
using namespace std;
class GameChar {
char * name;
int hp, mp, atck;
public: GameChar(char* _name, int _hp, int _mp, int _atck) {
name = _name;
hp = _hp;
mp = _mp;
atk = _atck;
}
char* stats() {
char * statStr;
sprintf(statStr, "%s | %i HP %i mp, and %i attack.", name, hp, mp, atck);
return statStr;
}
};
int main() {
GameChar alex = new GameChar("Alex", 200, 100, 20);
puts(alex.stats());
return 0;
}
I get:
C:\CPP Projects\CMD Line\main.cpp||In constructor `GameChar::GameChar(char*, int, int, int)':|
C:\CPP Projects\CMD Line\main.cpp|13|error: `atk' was not declared in this scope|
C:\CPP Projects\CMD Line\main.cpp|13|warning: unused variable 'atk'|
C:\CPP Projects\CMD Line\main.cpp||In function `int main()':|
C:\CPP Projects\CMD Line\main.cpp|25|error: conversion from `GameChar*' to non-scalar type `GameChar' requested|
||=== Build finished: 2 errors, 1 warnings ===|