• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 357
  • Last Modified:

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.
1 Solution
mccarlIT Business Systems Analyst / Software DeveloperCommented:
What do you mean by "input"? Input from where? Someone typing on the console, etc?
The norm is for strings to be null-terminated.  If so:

unsigned int x = strlen(str);
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,

searchsanjaysharmaAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

KuppingerCole Reviews AlgoSec in Executive Report

Leading analyst firm, KuppingerCole reviews AlgoSec's Security Policy Management Solution, and the security challenges faced by companies today in their Executive View report.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now