Reputation:
there is no problem here:
int *x;
x = (int *) malloc(0 * sizeof(int));
int value = 5;
x = (int *) realloc(x,(value)*sizeof(int));
But I cant do that for strings :\
I wanna do that for a y[] array, like this:
y[0]="hello"
y[1]="how are you"
how can I do that?
Upvotes: 0
Views: 1119
Reputation: 28241
You can actually do exactly what you need exactly like with integers:
typedef const char *c_string;
c_string *y;
y = (c_string *) malloc(0 * sizeof(c_string));
int value = 5;
y = (c_string *) realloc(y,(value)*sizeof(c_string));
y[0]="hello";
y[1]="how are you";
This won't work with non-const char *
though, so this example is of limited usability.
Upvotes: 0
Reputation: 114461
You cannot use realloc
on an array of std::string
objects because realloc
moves things around by bit copying and this is not allowed on general objects.
The standard class std::vector
is a generic container for objects that moves and copies things around correctly (using copy constructors, assignments and similar methods) and that can change its size for example with the resize
method. All the needed memory is allocated and freed automatically as needed.
With std::vector
for example you can write code like...
std::vector<std::string> v; // An empty vector
v.resize(10); // Now size is 10 elements (all empty strings "")
v[0] = "Hello"; // First element is now the string "Hello"
v[1] = "world."; // Second element is now the string "world."
v.resize(2); // Now v.size() is 2
v.push_back("How's going"); // Now the size is 3 and third element is filled.
Do yourself a favor and pick up a good C++ book, reading it cover to cover. C++ is a powerful but complex language and if you try to learn it by experimenting with a compiler you're making a terrible mistake for many reasons.
Upvotes: 2
Reputation: 32490
What you're doing right now is not C++ ... you can do what you want with C-style strings, but you would need an array of pointers to type char
that allow you to access the allocated memory for each string in the array. This can be done like so:
char* y[2];
y[0] = strdup("hello");
y[1] = strdup("how are you");
You also need to keep in mind that your y
array now "owns" the pointers, so you must call free()
on each pointer in the array in order to avoid any memory leaks should you decide to change the strings each pointer is pointing to.
If you want to go with an idiomatic C++ solution though, and not revert to C-style strings, then you should be using std::string
and std::vector
... doing so avoids the issues with memory leaks as well as allocating and deallocating the memory associated with dynamically allocated C-strings.
Upvotes: 1
Reputation: 129764
std::vector<std::string> y;
y.push_back("hello");
y.push_back("how are you");
Don't use malloc
, or realloc
, or free
in C++. Don't use char*
for purposes other than interop. Stay away from pointers until you actually need them (same for arrays).
Upvotes: 10