0

I atentionally keep optional details for a best undersanding. say we want to store a string in a variable of char* :

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    char * s;
    int n;
    do{
        printf("string's length: ");
        scanf("%d", &n);
    }while(n<=0);
    s = (char *) malloc((n+1) * sizeof(char));
    if(s!=NULL){
        printf("enter a string (length <= %d): ", n);
        gets(s);
        puts(s);
        free(s);
    }
    puts("end of programme.\n");
    return 0;
}

in this answer it says :

If you were to set s to point to a preexisting array or if you used malloc to allocate space, then you can write to it successfully.

so, despite all that, why the call to gets still doesn't success? how can we explain this behavior ?

Simo
  • 155
  • 3
  • 12
  • 1
    It does work. It reads the newline after the number. Please turn on and refer to all warnings when building your code – stark Dec 02 '21 at 15:51
  • Read the documentations and the uncounted questions here on SO on `scanf()` and `'\n'` left in the input. – the busybee Dec 02 '21 at 15:53
  • Looking at the return value of gets would also have answered your question. – stark Dec 02 '21 at 15:56
  • "still doesn't success?" What does that mean? Do you get compiler errors? Runtime errors? Wrong output? What is your input, your output and your expected output? "Does not work" or similar is not a useful description of any problem. – Gerhardh Dec 02 '21 at 16:01
  • It's kind of amazing that in a 50+ year old language, still no one came up with a more intuitive i/o facility, isn't it? :) So, @Simo - unless you are forced to, don't bother learning C. There are tons of friendlier languages around. – BitTickler Dec 02 '21 at 16:02
  • @BitTickler If only there were a standard library function that combined the best of `gets` and `fgets` — preventing buffer overflow, but stripping the `\n` — things would be *so* much easier for C learners. – Steve Summit Dec 02 '21 at 16:06

1 Answers1

1

The problem is that gets read the the buffer until a line break (\n), when you input a number, you press enter to confirm it, and the \n goes to the buffer. The gets read it and assume that's what you want. You need to throwaway the line breaker before call gets.

#include <stdio.h>
  #include <stdlib.h>
  int main(int argc, char *argv[]){
      char * s;
      int n;
      do{
          printf("string's length: ");
          scanf("%d", &n);
      }while(n<=0);
      scanf("%*c"); // throwaway a character, in this case, the line breaker
      s = (char *) malloc((n+1) * sizeof(char));
      if(s!=NULL){
          printf("enter a string (length <= %d): ", n);
          gets(s);
          puts(s);
          free(s);
      } 
      puts("end of programme.\n");
      return 0;
  }
riquefr
  • 260
  • 1
  • 7