-1

I have an array of size 100. I read string input from a the user and store it in the array. The user input is less than 100 characters. How would I create a new array which is the exact length of the input (without the trailing whitespace at the end)?

  • 1
    Please [edit] your question and copy&paste your code *as text*, formatted as a code block, instead of describing it. Show example input and expected output. See [ask] and [tour]. – Bodo Mar 21 '23 at 18:06
  • 1
    By trailing whitespace do you mean the characters 'wasted' by the length of the string or is the user literally giving blank characters as input? – Miguel Sandoval Mar 21 '23 at 18:27
  • 1
    The `strdup` function is one option (but it's not part of the standard C library). You can write your own `strdup` function using `strlen`, `malloc` and `strcpy`. Just be sure that you allocate `strlen(str) + 1` bytes of memory, so there's room for the zero byte at the end of the string. – user3386109 Mar 21 '23 at 18:33
  • 1
    @user3386109 `strdup` is a part of the upcoming C23 standard. – SafelyFast Mar 22 '23 at 01:48

1 Answers1

1

If you just want to get rid of the "unused" characters (those after '\0') and make an "exact copy":

#include <stdlib.h>
#include <string.h>

char *get_str(char *base) {
  char *result = malloc(strlen(base) + 1);
  if (!result) exit(1);
  return strcpy(result, base);
}

Don't forget to free the string once you are done with it!