Dynamic allocation of array as the user types the string.
This post is deleted!
and my english is bad ( which they consider a mistake as well lol )
English is the basic tool of software development. All languages and all docs are written primarily in English. I don't think it is wise to try to turn it into a joke. At the same time, it's worth to remember that for most programmers, English is a secondary language, so it's silly to consider that as a mistake. Everybody should have a chance to learn, after all.
OK, sorry for that digression. On to the topic:
the above program doesn't work why ?
How exactly does it fail? Crash? Username is empty at the end? It skips some chars? Fails to print the result (you have no final printf after the loop is done)?
Assuming the problem is with the reallocation itself: perhaps I should not mention it, but it is a very good idea to use some safe and ready-made components for such tasks. For example, containers like std::vector, or if you want to go the Qt way, the QVector. It will handle the memory automatically for you, and make it in a fast and efficient manner.
If you still want to go this way, however, here are my notes:
- I have not run your code, and quite frankly I've not used calloc/realloc for a looong time, so I'll be guessing a bit :) Take my hints with a grain of salt please
- calloc() requires 2 parameters, but you provide only one
- more crucially, realloc() will return a null pointer (or dereference the memory!) if size parameter is empty. It's not the case in your code, but something to watch out for
- this code may "break" on UTF-8 characters
- you never allocate memory for more than 1 character (always only for
sizeof(char*)). If you want to get a longer array, allocate for more characters:
length * sizeof(char*)(assuming you increment length first)
I suspect the last hint is what you need to do to make it work. Good luck!
your issue is the char is only 1 and your gonna keep relocating 1 char each time.
me personally i would use a for loop
for(char *username = 0; username < 15; username ++) // if size is less than 3 return else if size greater than 15 return // getche and calloc and length realloc it..