getting string with dynamic memory management
I wanna get string like 34,34;34,21;45,12;45,12(length is not certain.) I wanna dynamic memory allocation with realloc but i can't do it. How i can get like this characters to string??
it will 开发者_运维问答be string={34,34,34,21,45,12,45,12}
You will have to know the length beforehand, and when you know that your buffer is too small for data that is going to be newly entered, use:
realloc(ptr, newLength);
If you're looking to do this at compile time (which is the only way to perform initializers similar to what you have in your question), you can let the initializer define the size f your array:
char string[] = {34,34,34,21,45,12,45,12, 0}; // added a 0 to the end to
// make it '\0' terminated
// You might not need that
If you want your string to take it's data from a runtime source (a file or other input), you'll need to perform the allocation yourself, and exactly how to do it depends on how you're going to be getting the data.
The following example reads data from stdin
into a dynamically allocated character array, growing the array as needed until EOF is reached. It grows the array by 20 bytes each time so you can easily check what's happening in a debugger, but a real life program would do better to grow by something larger like by doubling the size or just growing in increments of 100KB - the details of your expected data should guide you in this decision).
#include <stdlib.h>
#include <stdio.h>
void fatal_error(void);
int main( int argc, char** argv)
{
int buf_size = 0;
int buf_used = 0;
char* buf = NULL;
char* tmp = NULL;
char c;
int i = 0;
while ((c = getchar()) != EOF) {
if (buf_used == buf_size) {
//need more space in the array
buf_size += 20;
tmp = realloc(buf, buf_size); // get a new larger array
if (!tmp) fatal_error();
buf = tmp;
}
buf[buf_used] = c; // pointer can be indexed like an array
++buf_used;
}
puts("\n\n*** Dump of stdin ***\n");
for (i = 0; i < buf_used; ++i) {
putchar(buf[i]);
}
free(buf);
return 0;
}
void fatal_error(void)
{
fputs("fatal error - out of memory\n", stderr);
exit(1);
}
Maybe you are passing the pointer as an argument to a function b() which is in turn calling the realloc In this case you need to also return the pointer.
精彩评论