Reputation: 3
I want the loop to break when "Enter" is pressed. Any suggestions?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define len 20
#define limit 100
//Prototypes for functions
int read_word(char str[], int n);
int main(void)
{
char *p;
char word[len+1];
int i=0, nwords = 0;
//Loop for reading in words and allocating an array
for (;;)
{
if (nwords == limit)
{
printf("Insufficient Space\n");
break;
}
printf("Enter word: ");
scanf("%c", &word);
p = (char*) malloc(nwords*sizeof(char));
p[i]= read_word(word, len);
i++;
if (p == NULL)
{
printf("Insufficient Space\n");
break;
}
}
for(i=0; i<nwords; i++)
printf(" %s\n", p[i]);
return 0;
}
int read_word(char str[], int n)
{
char ch;
int i = 0;
while((ch = getchar()) != '\n')
if (i<n)
str[i++] = ch;
str[i] = '\0';
return i;
}
Upvotes: 0
Views: 286
Reputation: 20631
Your scanf
call reads the first character, and then your read_word
function overwrites it. If the scanf
call reads the newline, it will then be ignored.
The lines:
p = (char*) malloc(nwords*sizeof(char));
p[i]= read_word(word, len);
... also appears wrong. read_word
returns an integer (the length of the string read), but you are storing into a char
array. Also, you are re-allocating the memory for p
each time through the loop, so the values stored previously will be lost.
To fix:
p
to be an int *
, and initialize it to nullmalloc
call to a suitable realloc
scanf
entirelyp == null
before the assignment of `p = (char*) malloc(nwords*sizeof(char));'Or: is p
meant to actually be an array of strings (the words themselves) rather than the word length? In that case you have to:
p
to be an char **
realloc
call) to nwords * sizeof(*p)
malloc
) storage for each word instead of having word
be a stack-allocated arrayp[i] = word;
rather than the current assignment.Upvotes: 1