Reputation: 961
Im fairly new to c sorry if this is a stupid question!
i have this:
fgets(question,200,stdin);
char *memq = malloc(sizeof(strlen(question)));
memq= question;
however the question variable always has a new line on the end of it ! how do i remove this / prevent it happening?
i have tried this:
fgets(question,200,stdin);
char *memq = malloc(sizeof(strlen(question))-sizeof(char));
memq= question;
there was no effect!
Upvotes: 1
Views: 4632
Reputation: 14376
to get rid of the newline, before your malloc, do :
question[strlen(question)-1] = 0;
an alternative (suggested in the comments below) would be to do the following instead:
question[strcspn(question, "\n")] = '\0';
change the malloc line to:
char *memq = malloc(strlen(question)+1);
change the assignation line:
memq = question;
to:
strcpy (memq, question);
Upvotes: 5
Reputation: 23
Hint: Remove the last character! (Hint to hint: you know the length)
Upvotes: 0
Reputation: 204668
In both cases, memq = question
is wrong. You've just lost your pointer to new newly-allocated space, and instead copied the address of the first character of question
to memq
Use strcpy
or memcpy
instead, to copy the contents of the string pointed to by question
to the contents of the memory pointed to by memq
.
Upvotes: 1
Reputation: 54128
This code is badly broken.
You need to allocate strlen+1
bytes into memq
if you plan to copy the data there (why are you doing sizeof
? that will allocate 4 bytes since sizeof(strlen())
is sizeof(int)
).
You cannot just assign question
to memq
and expect the data to be copied in. All this does is overwrite the pointer you just malloc
-ed into memq
, leaking it. You have to do
strcpy(memq, question);
That's why you need the extra byte in memq
, since this includes a null terminator. At this point you are in position to remove the newline from memq
as noted elsewhere.
Upvotes: 2
Reputation: 82559
Let's say your input is ABCDEn where the n represents the new line.
You're going to be reading in ABCDEn0 where 0 represents null, which terminates the string.
So, by taking off the last char, you're taking off the null, not the newline. I would take off the last char as you are, but then set the (new) last char to null to terminate your string.
Upvotes: 1