Any1 pls help!! memory allocation issue

char letter;
string astring;
cout<<"Enter a string: ";
cin>>astring;
// vector<char>word;

char *word = new char [astring.size()];
cout<<sizeof(word)<<endl;
......
.....delete [] word;
If I input for example "banana", the astring size is 6 which is correct, but when I cout the sizeof word is gives only 4, what is wrong?
sizeof() doesnt give the number of digits, it gives the size of that data type in bytes, eg a char is 4 bytes, an int is 4 bytes, a short is 2 bytes.

EDIT - sorry I should've said their sizes depend on the platform, if you're using a 64 bit system or something they might be different
Last edited on
closed account (zb0S216C)
Quirk is right. Also, if you don't already know, always make room for one extra character( null-terminated ) when allocating space for a string dynamically.

Note: If char *word is later re-used after delete [] word, make sure you set it to NULL after deleting it. This prevents an invalid memory address.
Last edited on
This prevents an invalid memory address.

rather, it prevents your program from exploding when you accidentally delete it again. Which isn't really what you want, you want to not delete the same thing twice.
Thank you so much Quirk and Framework!!!Very helpful.But.. (Below is the program that I've been stuck on, just if anyone who is interested, that would be great! )
I am working on expand function.Write a C++ command-line program that includes a main function and an expand function. The main function should ask the user to input a string and a character, output the original string, call the expand function, then output the expanded string. Funciton expand should not contain any cin or cout statements.
The signature of expand is
void expand(char str[], char mark);

Before expansion: banana
After expansion: ba na na

(My issue is it print out:
Before expansion: banana
(space)After expansion: banan

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
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void expand(char str[],char mark)
{
	cout<<sizeof(str)<<endl;
	for(int i=0;i<=sizeof(str);i++)
	{
		if(str[i] == mark)
		{
			cout<<" ";
		}
	}
}

int main ()
{
	char letter;
	string astring;
	cout<<"Enter a string: ";
	cin>>astring;
//	vector<char>word;
	char *word = new char [astring.size()];
	for(int i=0;i<astring.size();i++)
	{
//		word.push_back(astring[i]);
		word[i] = astring[i];
	}
	if(word == 0)
		cout<<"Error!"<<endl;
	
	cout<<"Enter a character that exists in the string: ";
	cin>>letter;
//	for(int k=0;k<=word.size();k++)
//	{
//		cout<<word[k];
//	}
	cout<<"Before expansion: "<<word<<endl;
	
	expand(word,letter);
	
	cout<<"After expansion: ";
	for(int j=0;j<=sizeof(word);j++)
	{
		cout<<word[j];
	}
	cout<<endl;

	delete [] word;
    return 0;
}
Last edited on
Topic archived. No new replies allowed.