How to create this dynamic char array to save memory space?

Hi there! I have created a simple console-rpg-battle simulator and I need to recreate the name so it is gathered dynamically, not to take up more space than necessary. I have tried all day and don't really know how to get it to work.
The code I use at the moment takes up more space than necessary. and This is the code that I use at the moment, but it wastes memory.

Can you help me go towards the correct path? Name needs to have 3 parts "Firstname Secondname of thirdname". For instance, slimy dagger of doom.

I need to somehow use "new char[characterLength +1]"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  //my weapon.h code:
#ifndef WEAPON_H
#define WEAPON_H
#include<iostream>
#include<string.h>
#include<ctime>
#include<stdlib.h>
#include <stdio.h>
#include <ctype.h>

using namespace std;

struct Weapon				//structures
{
char name[50];
int minDamage;
int maxDamage;
int temp; 
};

Weapon* createWeapon();
void showWeaponInfo(Weapon *w);
void destroyWeapon( Weapon *w );

#endif 




//my weapon.cpp code
#include"Weapon.h"


Weapon* createWeapon() //Create Weapon
{
Weapon *w = new Weapon; 
w->minDamage = rand() % 7+5;
w->maxDamage = rand() % 7+13;
w->temp = w->maxDamage - w->minDamage;  


char firstWord[][15] = {"Fabulous ", "Puny ", "Moldy ", "Slimy ", "Delicious "};
char secondWord[][15] = {"Blade ", "Butterknife ", "Foot ", "Lantern ", "Axe "};
char thirdWord[][25] = {"of the Hamster", "of the Madonna", "of promiscuity", "of the squirrel", "of obesity"};

strcpy_s(w->name, firstWord[rand() % 5]);
strcat_s(w->name, secondWord[rand() % 5]);
strcat_s(w->name, thirdWord[rand() % 5]);

return w;
} 

void showWeaponInfo(Weapon *w)			//Show Weapon
{
cout << "Weapon Name: " << w->name << endl; 
cout << "Weapon damage: " << w->minDamage << " - " << w->maxDamage << endl;
}



void destroyWeapon( Weapon *w )			//Destroy Weapon
{
	delete w; 
}


Thank you for reading my code, and I appreciate any help that I can get.
use new style headers:
1
2
3
#include <cstdlib>
#include <cstdio>
#include <string> 


i would suggest using the C++ string class rather than the C string.
1
2
3
4
5
struct Weapon
{
    string name;
    . . .
}

the string class is smart about this thing, and handles this automatically:
1
2
3
(w->name).assign(firstWord[rand() % 5]);
(w->name).append(secondWord[rand() % 5]);
(w->name).append(thirdWord[rand() % 5]);
Thanks mate, I'll give this a try right away. :) Highly appreciated!
Topic archived. No new replies allowed.