ekaf ekaf - 1 year ago 77
C Question

what will be happen to the size of string in this code?

#include <stdio.h>
#include <stdlib.h>

int main()
int size=10;
char string1[50];
char *string2;
string2=(char *)malloc(size*sizeof(char));




There are two strings in this code one is an array and another one is dynamically created using pointer.

  1. If my input is less than 50 for string1 and less than 10 for string2 will the space that is not filled get wasted ,if so how to reduce the size.

  2. In case of string 2 malloc size parameter is 10 and fgets size parameters is 10 what will happen if i increase the size to fgets(string2,50,stdin) which is greater than malloc's size?

  3. how to calculate the final size of input string in each case?I have used sizeof operator but it gave the hardcoded size that is 50 and 10 respectively for string1 and string2

  4. Is there any other better approach to create a dynamic string?

Answer Source
  1. Yes, it will be wasted. You can use variable-length arrays to use a different limit, or use dynamic allocation. Whether or not you should worry about the wasted space is a separate question: if your program reads strings that the user inputs manually (as opposed to reading a file) you can waste a lot of space before it starts to matter, unless you are on an embedded system with severe memory constraints.
  2. You will get undefined behavior, so your program will be invalid. Don't do that - it is precisely why fgets takes the maximum length of the string.
  3. Call strlen to compute the length of the string. Add 1 for null terminator. Remember that '\n' is part of the string when you use fgets and the input has '\n' in it.
  4. You can use POSIX extension to scanf, and pass %ms format and a pointer to char*. This will allocate the string at the exact length, but your program will be less portable. Obviously, you are required to deallocate these strings to avoid memory leaks.