-5

I have been curious to know How to decide string length ?
When I asked my teacher this, he replied "you have to assume a value and allocate to srting".
which eventually pushed me to my original question how to assume a specific length for a string. I used to think about memory allocation, i.e We are usually write

char str[50] = "Hello world";

Here compiler allocates 50 bytes of memory for string str but only 10 bytes will be used and remaining 40 byte is wasted.

So is there any way to allocate memory after user inputs the string?

  • 4
    Just use `std::string` to get rid of a lot of worries – JVApen Jan 22 '19 at 07:09
  • 8
    First, C and C++ are two very different languages, with different semantics for many things. Even if something is the same (or almost the same) in both languages please only tag the one you're actually programming in. Especially when it comes to strings there are some subtle differences for some things, and in C++ one should never really use C-style strings anyway. – Some programmer dude Jan 22 '19 at 07:10
  • As for your problem, there are functions in both languages that determine the length of all ***null-terminated** byte strings*. – Some programmer dude Jan 22 '19 at 07:11
  • Drop/Ignore your teacher. – Swordfish Jan 22 '19 at 07:19
  • @Someprogrammerdude - I think the (poorly phrased) question is how to determine the buffer length in advance for taking a string as input – StoryTeller - Unslander Monica Jan 22 '19 at 07:19
  • @StoryTeller easy: `std::string line; std::getline(std::cin, line);` – Swordfish Jan 22 '19 at 07:20
  • 1
    Are you asking for C or C++, because what's appropriate in C++ (`std:;string`) doesn't exist as such in C. In C, you might have the `m` modifier available in `scanf()` and family, which allocates enough space automatically. That isn't universally available on Unix-like machines (it isn't available in macOS 10.14 Mojave, for example), but where it is available, it is fiendishly useful. – Jonathan Leffler Jan 22 '19 at 07:21
  • 1
    If you want to know if you can determine the length beforehand (as suspected by @StoryTeller) then the answer is no. And for how to solve or work around that, now the issue about language really comes into play as the natural solution would be *very* different between C and C++. – Some programmer dude Jan 22 '19 at 07:21
  • @Swordfish - There's the C tag too. Not quite as easy. – StoryTeller - Unslander Monica Jan 22 '19 at 07:21
  • @StoryTeller Yes, one of the two tags should be removed. – Swordfish Jan 22 '19 at 07:26
  • 4
    This question really is unclear just for the small mistake of tagging C AND C++. We could guess what you really need, if you had shown code, e.g. a [mcve] of a program which could benefit from a solution proposal. – Yunnosch Jan 22 '19 at 07:32
  • On a more personal note, even though you asked a few questions you don't seem to have spent any time reading [the help pages](http://stackoverflow.com/help), especially ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the SO tour](http://stackoverflow.com/tour), then [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) and [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jan 22 '19 at 07:39
  • I have edited the post now please do check and help me out please – sachin mirajkar Jan 22 '19 at 08:55
  • @sachinmirajkar Read Stroustrup's [C implementation here](http://www.stroustrup.com/new_learning.pdf). So of course you can allocate memory incrementally while characters are inputted, but you have to write a somewhat sophisticated input routine to do it. – PaulMcKenzie Jan 22 '19 at 09:29
  • @sachinmirajkar `"Hello world"` string literal occupy 12 bytes. 11 characters and trailing `\0` to make it string in C – EsmaeelE Jan 27 '20 at 08:13
  • @EsmaeelE Yes you are right, but the thing is remaining 38 bytes will be wasted. and if I give a string of length then it will through a error. So my question is how to allocate dynamic length of an string. i.e in C++ we just specify `string str = "Hello world"` which allocates only 12 bytes to `str` like wise i want to do it in C language – sachin mirajkar Jan 27 '20 at 08:52
  • @sachinmirajkar use this `char str[]="Hello world"; printf("%zu", sizeof(str));` – EsmaeelE Jan 27 '20 at 11:28
  • @EsmaeelE It is a good idea when I am initializing a string but what to do when I am getting user input from std IO's – sachin mirajkar Jan 27 '20 at 14:21
  • @sachinmirajkar I don't know is there any standard library function to do that (I think No)([cs50](https://man.cs50.io/3/get_string) have one) but you can use this Implementation by hand, this version with `realloc()+free()` [BLUEPIXY answer](https://stackoverflow.com/a/16871702/7508077) Also Jonathan Leffler answer similar question [in](https://stackoverflow.com/a/3598447/7508077) this he said : Use POSIX [`getline()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html) – EsmaeelE Jan 28 '20 at 13:32
  • I don't know why this question receive many down-votes. – EsmaeelE Jan 28 '20 at 14:45
  • @EsmaeeIE I was new to this flattorm and structured this question wrongly. But now I have made correction. And because of downvotes, I am not able to ask new question – sachin mirajkar Jan 29 '20 at 03:01

1 Answers1

2

We used to give input about 20 to 30 input max so remaining are wasted

That's right. There's no limit to how much you can allocate, but if you know that you won't need more than a certain amount, then you can just allocate that much. Usually for a Hello World running on a modern PC you're not strapped for memory, but if you store millions of records with names and so on in a database, it's good to think about memory consumption.

I even asked teachers is there any way that I can decler array size dynamically so that he replied answer "No" please help

You can allocate memory dynamically. Suppose you have code like this:

int n = 30;
char *string = malloc(n);
free(string); // any memory allocated with malloc should be freed when it is not used anymore

Now string has a size of 30 because that's what n was set to, but it could be anything else, determined at runtime. It could be something that the user has inputted.

In C++ there's a construct called std::string that automatically does the dynamic memory allocation for you. You can do something like

std::string s = "Hello";
s += " World";

And you don't even have to worry about memory allocation. If it doesn't fit internally, it will reallocate the memory on its own with an amortized constant runtime.

Blaze
  • 16,736
  • 2
  • 25
  • 44