gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:31 26 4
gpt4 key购买 nike

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

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

最佳答案

除了分配的大小问题(在table的分配中应该是sizeof(char*),和sizeof(int*) 中分配频率),

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;

你在调用者中分配的。

关于c - 使用C的频率阵列动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com