I need to write a program in C that gets a char array (sentence) and returns an array that each index contains the first letter of each word in the sentence.
I wrote an algorithm for it (which I hope is correct) but for some reason, when I activate the functions printf()
and gets()
, and run the program, the program runs without even printing or getting any input, and ends.
can you tell me the problem? I couldn't find it even with debugger:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *FirstLetters(char *sent)
{
int i = 0, counter = 1, *firstchar, *p = sent, *q;
while (*p != '\0')
{
if (*p == ' ')
counter++;
p++;
}
firstchar = (char *)malloc(counter);
q = firstchar;
*q = sent[0];
for (p = sent + 1, q = firstchar + 1; *p != '\0'; p++, q++)
{
if (*p == ' ')
{
*q = *p + 1;
q++;
}
}
return firstchar;
}
void main()
{
char sentence[SIZE], *firstletter, *p;
printf("Enter a sentence: ");
gets(sentence);
firstletter = FirstLetters(sentence);
printf("The result is: \n\n");
puts(firstletter);
}
I tried getting the input for the sentence using for loop with scanf_s
, but still, the program runs and ends without doing anything