• C

How to read a string in c dynamically,

void main()
{
         char str[2000];
}
Other way could be
void main()
{
          char *str=(char*)malloc(sizeof(char)*(no.of characters));
}
How can i get the no. of characters in c at runtime.

Is there any way to input a string dynamically without fixing the size.
searchsanjaysharmaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
What do you mean by "input"? Input from where? Someone typing on the console, etc?
0
KwoofCommented:
The norm is for strings to be null-terminated.  If so:

unsigned int x = strlen(str);
0
ZoppoCommented:
Hi searchsanjaysharma,

AFAIK there's no standard function to retrieve the size of a buffer allocated with malloc, allthough depending on the OS you're working on there may exist a function like i.e. _msize in Windows.

So the best way would be to store the size used with malloc somewhere if you need it later on. You could i.e. implement a struct with a char* and an int to handle this.

BTW, something about strings in C: Strings in C are representated as pointers to the first character where after the last character a terminating NULL character is added. So, if you want to be able to use the char *str with any string functions you need to allocate one extra char for the terminating NULL char, i.e.:
   char *str=(char*)malloc(sizeof(char)*(no.of characters + 1));
Then you need to copy the characters into the buffer and set the char after the last character to 0.

Hope that helps,

ZOPPO
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
searchsanjaysharmaAuthor Commented:
tx
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.