我正在编写如何为n个字符串动态分配内存,但是每个字符串都可以很长。因此,我知道使用双指针,但不了解如何为每个字符串分配适当的空间。我的代码:
int i,n;
char **str;
printf("Enter n (strings of chracters): ");
scanf("%d",&n);
str = (char**)malloc(n*sizeof(char*));
printf("Enter strings one by one:\n");
for(i=0; i<n; i++) {
str[i] = (char*)malloc(//SOMETHING//*sizeof(char));
gets(str[i]);
}
我试图厚脸皮,首先将gets()像这样
for(i=0; i<n; i++) {
gets(str[i]);
str[i] = (char*)malloc(strlen(str[i])*sizeof(char));
但是这显然是错误的,我无法读取字符串然后进行分配。那么,是否有必要用每个字符串的长度替换// SOMETHING //?感谢您阅读我的业余帖子。
您无法神奇地“预测”用户输入字符串之前需要多长时间!但是,您可以分配给定最大长度的“工作缓冲区”,读入该长度,然后分配所需的内存并复制该字符串。
您可以使用for (i = 0; i < n; ++i)
{
size_t current_size = 1; // Start with space for one character, the null-terminator
str[i] = malloc(current_size);
str[i][0] = '\0'; // String null-terminator
int ch; // Must be an int for the EOF check to work
// Read characters one by one, until eof (or error) or newline
while ((ch = getchar()) != EOF && ch != '\n')
{
char *temp_str = realloc(str[i], current_size + 1); // Increase memory by one character
if (temp_str == NULL)
{
// Error allocating memory, do something useful here
break;
}
str[i] = temp_str;
str[i][current_size - 1] = ch; // Add the newly read character
str[i][current_size] = '\0'; // Add the new null-terminator
++current_size; // Increase the size
}
}
,malloc
和strlen
的组合来执行此操作,但是strcpy
功能可以一口气为您完成所有操作:
strdup
[此外,如注释中所述,strdup
函数已从C库中删除:改为使用#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLENGTH 5000
int main()
{
int i, n;
char** str;
char buffer[MAXLENGTH]; // Working buffer to read in strings
printf("Enter n (strings of chracters): ");
scanf("%d", &n);
str = malloc(n * sizeof(char*));
printf("Enter strings one by one:\n");
for (i = 0; i < n; i++) {
fgets(buffer, MAXLENGTH, stdin);
// You may want to remove the trailing newline from the string
str[i] = strdup(buffer);
}
for (i = 0; i < n; i++) printf("%s\n", str[i]);
for (i = 0; i < n; i++) free(str[i]);
free(str);
return 0;
}
(如图所示)。参见:gets
。
此外,您也无需强制转换fgets()
:Why is the gets function so dangerous that it should not be used?的结果。