I want the loop to break when "Enter" is pressed. Any suggestions?
#include <stdio.h>
#include <st开发者_JS百科dlib.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;
}
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:
- change
pto be anint *, and initialize it to null - change the
malloccall to a suitablerealloc - remove the call to
scanfentirely - move the check for
p == nullbefore 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:
- change
pto be anchar ** - change the allocation size (for the
realloccall) tonwords * sizeof(*p) - allocate (using
malloc) storage for each word instead of havingwordbe a stack-allocated array - set
p[i] = word;rather than the current assignment.
加载中,请稍侯......
精彩评论