Reputation: 9
This is a very complex idea I am working with I suppose
int capacity = 100;
name = malloc(capacity * sizeof(char));
int len = 0;
char* i;
for (i = str; *i; i++) {
if (len >= strlen(name)) {
capacity *= 2;
name = realloc(name, len * sizeof(char));
}
len++;
}
Assume name
is declared already as a char pointer and str
is passed in as a parameter. Why would this not work to double the size of an array?
Another approach I took was
int nameLength = 0;
int capacity = 100;
char* name = NULL;
double price = 0.0;
int position = 0;
if (sscanf(str, "add %s %lf %n", name, &price, &position)) {
nameLength = capacity - position;
capacity += nameLength;
name = realloc(name, capacity * sizeof(char));
} else {
name = malloc(REMAINING_MAX * sizeof(char));
}
Where I tried to take advantage of the %n
format specifier.
Upvotes: 0
Views: 51
Reputation: 3707
strlen
is used to know how many useful character are stored inside a string. For that, it count how many char are set before viewing NULL char which terminate the string \0
(the sentinel).
You are passing an uninitialized value to this function: this is a Undefined Behavior. Indeed, name
is initialized with malloc
but allocated memory (ie value pointed by name) still uninitialized! String pointed by name can store any kind of values. And it is impossible to know what will happen: it will fail, or if you are not lucky it will run correctly (until, a future crash). So NEVER use unitialized value.
So, to remember capacity, you have to store it. An good approach is to store both pointer and capacity to a structure to be sure that both are never separated:
struct ResizeableString {
size_t capacity;
char * str;
};
Upvotes: 1