c - 每个字符串长度的动态 n 个字符串是随机的(取决于用户输入)
问题描述
我正在写如何为 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//?感谢您阅读我的业余帖子。
解决方案
如果您不想浪费空间并且只分配足够的内存来容纳字符串,那么您需要逐个字符地读取,直到您读取换行符,realloc
并根据需要重新分配(使用)。
也许是这样的:
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
}
}
推荐阅读
- javascript - jspdf 和 html2canvas:未正确显示选定的单选按钮
- amazon-web-services - 在 AWS 账户之间切换
- minecraft - CraftTweaker (Minecraft 1.16): 损坏和重用以及制作后的物品
- android - 为什么我不能在“BoxScope”中使用“AnimatedVisibility”?
- python - 在 os.system 之后 python 脚本不会继续
- spring - 如何将 webclient 响应转换为 ResponseEntity?
- django - 在 Django 中验证之前,是否可以从表单集中获取数据作为字典列表?
- python - 在我出于无知而将其卸载后尝试在centos 7上安装python 2.7.5
- javascript - Peerjs 流重复(发送两次或更多次),有时不显示任何流
- html - 图像标签和段落标签之间的固定距离