I am a beginner in C and I created a program which does the following :
- read input from keyboard .
- store the words to a dynamically allocated array until read the word bag
- print the first word of the array
When I replace the break statement with return I notice that does not print the first word of the array in contrast with break statement (Why is this happened?)
In case of return :
If I have the following input
- vld
- pkd
- lok
- bag
At the moment which input is bag everything is stored in array (I mean the words vld,pkd ,lok) is lost?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void word() {
int num = 0 , i = 0;
char s[10];
char **str;
for(;;)
{ gets(s);
if (strcmp(s ,"bag")== 0 )
{
break; // return;
}
}
num++;
str = (char **)malloc(sizeof(char*)*num);
str[num - 1] = (char*)malloc(sizeof(char)*strlen(s)+1);
str[num - 1] = strdup(s);
printf("the word is : %s",str[0]);
}
int main()
{
word();
return 0;
}