Home > database >  Having troubles understanding string declaration in C
Having troubles understanding string declaration in C

Time:12-25

I'm having some trouble understanding a string declaration in C using dynamic memory.

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

char *putText(){
    
    char *s=(char *) malloc(256 sizeof(char));
    for(int i=0; *(s i); i  ) *(s i)=getchar();
    return s;

}

void main(){
    
    printf("Write the text: ");
    char *s=putText();
    printf("%s", s);
    
}

In this function, I'm trying to declare the string using getchar() in a for loop, but when I try to print the string, it always stops at the third character. I am still a newbie, so I've probably made some mistake. Can someone help?

CodePudding user response:

The allocated memory in this declaration

char *s=(char *) malloc(256 sizeof(char));

can contain any garbage.

So the condition in the for loop

for(int i=0; *(s i); i  ) *(s i)=getchar();

does not make a sense.

Instead you could write for example

int c;

for ( size_t i=0; i   1 < 256 && ( c = getchar() ) != EOF && c != '\n'; i   )
{
    *( s   i ) = c;
}

*( s   i ) = '\0';
  • Related