在 C 中使用 malloc 创建字符串数组

Creating an array of strings using malloc in C

我完全是 C 的新手,刚刚了解了使用 malloc、realloc、calloc 和 free 的动态内存分配。

我想制作一个小程序,它将一个整数作为将要给出的字符串的数量,然后 "scanf" 所有这些。 接下来玩这些字符串。例如找到最频繁的并打印出来。
例如,当我 运行 程序并输入 :
5
车屋狗树树
它应该打印:
树 2

我想要 scanf-printf,因为这是我目前最熟悉的 input/output 方法。
我的代码:

int main (){

int N,i,j ;

char *array;

int *freq;


 scanf("%d",&N);

 array = (char*)calloc(N,sizeof(char*));
 for (i=0;i<=N;i++){    
  scanf( ??? );  
 }

 free(array);  
 return 0;  
}

为了用字符串正确填充数组,我应该在 scanf 函数中输入什么? 在我填写它之后,我会使用类似 strcmp 和 for 循环的东西来扫描数组并找到最频繁的单词吗? (我可以将频率存储在 *freq 中)

您想分配一个字符串数组,换句话说,一个指向字符的指针数组,这正是您要分配的内容。问题是您将 calloc 返回的指针分配给 个字符的数组

实际上您在这里有两个选择:要么将您的 array 声明更改为指向字符的 "array" 指针,例如char **array,然后动态分配各个字符串。像这样

// Allocate an array of pointers
char **array = calloc(N, sizeof(*array));

// Allocate and read all strings
for (size_t i = 0; i < N; ++i)
{
    // Allocate 50 characters
    array[i] = malloc(50);  // No need for `sizeof(char)`, it's always 1

    // Read up to 49 characters (to leave space for the string terminator)
    scanf("%49s", array[i]);
}

或者您可以将 array 的类型更改为指向固定大小 "strings" 的指针,像这样

// Define `my_string_type` as an array of 50 characters
typedef char my_string_type[50];

// Declare a pointer to strings, and allocate it
my_string_type *array = calloc(N, sizeof(*array));

// Read all strings from the user
for (size_t i = 0; i < N; ++i)
{
    // Read up to 49 characters (to leave space for the string terminator)
    scanf("%49s", array[i]);
}

注意我don't cast the result of calloc or malloc。你不应该在 C.

中使用 void *

在 scanf 函数中,您需要 select 一种格式和您希望数据进入的数组。例如:

scanf("%[^\n]", array); 

您需要确保输入的大小不超过您应用的大小,尝试scanf("%s",array);