c - 在 C 中动态分配内存时出现错误
问题描述
我在以下代码中遇到分段错误(核心转储):-
#include <stdio.h>
#include <stdlib.h>
int main()
{
char text[100];
int max = 0,ctr = 0;
int j=0;
printf("Enter the text: ");
gets(text);
int tokens = 1;
for (int i =0; text[i] != '\0'; i++)
{
if (text[i] == ' ')
tokens ++;
ctr = 0;
while (text[j] != ' ')
{
ctr ++;
j++;
}
if (max < ctr)
max = ctr;
j++;
}
int r,c,p=0;
r = malloc(sizeof(char)*tokens);
c = malloc(sizeof(char)*max);
char token[r][c];
for (int k = 0; text[k] != '\0'; k++)
{
if (text[k] = ' ')
{
p++;
continue;
}
token[p][k] = text[k];
}
for (int k = 0;k < r; k++)
{
for (int z=0; z<c; z++)
printf(" %c",token[k][z]);
printf("\n");
}
return 0;
}
问题是 :-
给定多行文本,解析文本以分隔标记。记号是由空格分隔的单词。将标记存储为最大长度未指定的单个字符串。维护一个指向每个字符串的一维指针数组。让一维数组的长度取决于令牌的数量。此外,每个令牌的内存分配应取决于每个令牌中的字符数。
解决方案
推荐阅读
- javascript - Req.file 是未定义的nodejs multer
- c# - ASP.NET Core 5 API 属性中的通用日志记录
- java - 获取数组中的联系人列表
- javascript - WordPress 类别、子类别、活动类别问题
- java - 我们可以为了方法级别的单元测试而将方法的访问说明符从私有更改为默认吗
- ios - 如何使用 Snap-kit 插入圆形微调器
- javascript - 如何在 Node/Express 应用程序中检测浏览器或选项卡关闭?
- oracle-jet - 我们如何从 OJet (Oracle JavaScript Extension Toolkit) 7.x 升级到 10.0?我们在哪里可以找到 10.0 版的 oraclejet.zip?
- javascript - NG0301:未找到名称“ngModel”的导出
- html - 复选框在行上对齐