首页 > 解决方案 > 在 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;
}

问题是 :-

给定多行文本,解析文本以分隔标记。记号是由空格分隔的单词。将标记存储为最大长度未指定的单个字符串。维护一个指向每个字符串的一维指针数组。让一维数组的长度取决于令牌的数量。此外,每个令牌的内存分配应取决于每个令牌中的字符数。

标签: cdynamic-memory-allocation

解决方案


推荐阅读