سؤال

I want to have a string(can contain spaces) as input. I want to do dynamic allocation. Structure of my program is somewhat like this.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct msgclient
{
    int msglen;
    int msgtype;
    char *cp;
}M1;

int main()
{
    M1 *m;
    m=malloc(sizeof(M1));
    m->msglen=5;
    m->msgtype=6;
    printf("Enter\t");
    fgets(m->cp,50,stdin);  //here
    // m->cp[strlen(m->cp)]='\0';

    printf("\n%d\n%d\n",m->msglen,m->msgtype);
    fputs(m->cp,stdout);
    return 0;
}

I want to know how to get input. Is there any way that the second argument of fgets be dynamic?

هل كانت مفيدة؟

المحلول

Use getline(3) -instead of fgets(3)- which reads a dynamically allocated line.

typedef struct msgclient {
  ssize_t msglen;
  int msgtype;
  char *cp;
}M1;

then in your main function

M1 *m;
m=malloc(sizeof(M1));
if (!m) { perror("malloc"); exit(EXIT_FAILURE); };
m->msglen=0;
m->msgtype=6;
m->cp = NULL;
printf("Enter\t");
fflush(stdout);
size_t msgsize = 0;
m->msglen = getline(&msg->cp, &msgsize, stdin);

you might consider adding the allocated size of the buffer (i.e. msgsize) as an additional field of struct msgclient

addenda:

Notice that you might perhaps consider using GNU readline. It offers edition and completion facilities (when reading from a terminal).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top