使用C的频率阵列动态分配

时间:2013-02-27 21:19:34

标签: c

我有一个函数遍历我的字符串数组,以找出字符串在数组中出现的次数。如果找到,则字符串将设置为NULL,并且计数器会跟踪找到字符串的次数。然后我在循环中调用另一个函数来为我的频率数组分配内存,以便我可以存储count。它似乎工作正常,但当我去主要我的程序崩溃创建任何其他变量。这是我的两个功能:

int search(char **table, int **frequency, int wordSize)
{
//  Local Declaration
int i, j, k;
int count = 1;
int strCount = 0;
char target[25];

// Statement
for(i = 0, k = 0; i < wordSize; i++)
{
    if(table[i] != NULL)
    {
        strcpy(target, table[i]);
        for(j = i + 1; j < wordSize; j++)
        {
            if(table[j] != NULL &&
               strcmp(target, table[j]) == 0 &&
               target != table[i])
            {
                count++;
                free(table[j]);
                table[j] = NULL;
            }
        }
    strCount += makeFreq(frequency, k, count);
    k++;
    }
    count = 1;
}

return strCount;
}// search


int makeFreq(int **frequency, int k, int count)
{
//  Local Declaration
int strCount = 0;

//  Statement
frequency[k]=(int*)malloc(sizeof(int));
frequency[k][0] = count;
strCount += 1;

return strCount;
}// makeFreq

有人能解释一下我的程序崩溃的原因吗?

这里我为我的桌子分配了1000个指针。

char** getPoint(void)
{
//  Local Declaration
char **table;

//  Statement
table = (char**)calloc(MAX_SIZE + 1, sizeof(char));
if(table == NULL)
{
    MEM_ERROR, exit(100);
}

return table;
}// getPoint

比我读过,我为文件中的字符串分配内存并将其存储到字符串数组中。

int scanFile(char **table, FILE *fpFile)
{
//  Local Declaration
int count = 0;
char temp[500];
char **ptr = table;

//  Statement

//  scan file, allocate, and copy string to array.
while(fscanf(fpFile, "%s", temp) != EOF)
{
    *(ptr + count) =(char*)calloc(strlen(temp)+1, sizeof(char));
    strcpy(*(ptr + count), temp);
    count++;
}

return count;
}// scanFile

以下是我为频率数组分配指针数组的方法。

void aloFreqAry(int **frequency, int wordSize)
{
//  Local Declaration

//  Statement
frequency =(int**)calloc(wordSize + 1, sizeof(int));
if(frequency == NULL)
{
    MEM_ERROR, exit(103);
}

return;
}// aloFreqAry

2 个答案:

答案 0 :(得分:3)

除了分配大小的问题(在sizeof(char*)的分配tablesizeof(int*)分配frequency时应该void aloFreqAry(int **frequency, int wordSize) { // Local Declaration // Statement frequency =(int**)calloc(wordSize + 1, sizeof(int)); if(frequency == NULL) { MEM_ERROR, exit(103); } return; }// aloFreqAry

frequency

不会向调用者中的int**分配任何内容。它只是将内存分配给该指针的本地副本,并在函数返回时丢失该句柄。

该函数应返回一个

,而不是将frequency = calloc(wordSize + 1, sizeof(int*)); // size of a _pointer_ to int if(frequency == NULL) { MEM_ERROR, exit(103); } return frequency; 作为参数
{{1}}

您在来电者中分配。

答案 1 :(得分:1)

这句话看起来很可疑(你说“我在这里为我的桌子分配了1000个指针”):

table = (char**)calloc(MAX_SIZE + 1, sizeof(char));

这看起来不像指针的分配,而是char缓冲区的分配。

也许你的意思是:

table = (char**)calloc(MAX_SIZE + 1, sizeof(char*));