我需要编写一个C函数,它从用户那里获取他想要输入的单词的数量,然后该函数必须从用户扫描单词,但是在数组中扫描它们。
例如:
程序:
number of words:
用户:
3
hi
my
name
(在每个单词之间有输入)然后该函数必须将这些单词放入 字符串数组(数组的大小必须由malloc定义,字符串的最大大小为100(可能更小))。
int main()
{
int n;
printf("Please enter the number of words: \n");
if (scanf("%d",&n)!=1)
return 0;
char *name;
name = malloc((sizeof(char)*100*n));
int c;
int i;
int m;
for (i = 0; i < n && ((c=getchar()) != EOF );i++)
{
name[i] = c;
}
finds_themin(&name, m); //I know this work
return 0;
}
答案 0 :(得分:0)
当你需要存储一个字符串数组时,需要一个char*
或char**
数组来指向每个字符串(char数组)。
char **name;
name = malloc(n); // to store n strings.
然后在循环中使用fgets
将输入读作一行。此外,您需要为每个新的char
数组分配内存。
fflush(stdin);
for (i = 0; i < n; i++) {
name[i] = malloc(100); // allocating memory for string.
fgets (name[i], 100, stdin); // 100 is the max len
}
然后,您可以简单地遍历char**
数组,i
索引将指向i
字符串。
for (i = 0; i < n; i++) {
// printf("%s", name[i]);
}
答案 1 :(得分:0)
您需要设置指针指针。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char **s;
int n;
char buffer[64];
fgets(buffer,64,stdin);
n=strtol(buffer,NULL,10);// I avoid using scanf
s=(char **)malloc(sizeof(char*)*n);// you need to declare a pointer to pointer
/*
'PtP s' would look like this:
s[0]=a char pointer so this will point to an individual string
s[1]=a char pointer so this will point to an individual string
s[2]=a char pointer so this will point to an individual string
....
so you need to allocate memory for each pointer within s.
*/
int i;
for(i=0;i<n;i++){
s[i]=(char*)malloc(sizeof(char)*100);// length of each string is 100 in this case
}
for(i=0;i<n;i++){
fgets(s[i],100,stdin);
if(strlen(s[i])>=1){// to avoid undefined behavior in case of null byte input
if(s[i][strlen(s[i])-1]=='\n'){ // fgets also puts that newline character if the string is smaller than from max length,
s[i][strlen(s[i])-1]='\0'; // just removing that newline feed from each string
}
else{
while((getchar())!='\n'); //if the string in the command line was more than 100 chars you need to remove the remaining chars for next fgets
}
}
}
for(i=0;i<n;i++){
printf("\n%s",s[i]);
}
for(i=0;i<n;i++){
free(s[i]); //avoiding leaks
}
free(s);
}