我想从c。
中的结构返回一个字符数组,一个整数数组我的数据结构如下:
struct character_frequency
{
char *characters;
int *frequency;
};
struct character_frequency collect_character_distribution(char *buffer, long lSize);
struct character_frequency collect_character_distribution(char *buffer, long lSize)
{
printf("Collecting character distribution...\n");
char distribution[256][2];
char *characters;
int *frequency;
long for_a;
int for_b;
struct character_frequency resultx;
for (for_a = 0; for_a < lSize; for_a++)
{
distribution[(int)buffer[for_a]][0] = (char) buffer[for_a];
distribution[(int)buffer[for_a]][1]++;
}
int cntr = 0;
for (for_b = 0; for_b < 256; for_b++)
{
if (distribution[for_b][1] > 0)
{
characters[cntr] = distribution[for_b][0];
frequency[cntr] = distribution[for_b][1];
}
}
resultx.characters = (char *) characters;
resultx.frequency = (int *) frequency;
return resultx;
}
我的主要功能如下:
int main()
{
char *buffer;
long lSize;
char *characters;
int *frequency;
struct Bar result = funct();
buffer = result.x;
lSize = result.y;
struct character_frequency characterFrequency = collect_character_distribution(buffer, lSize);
characters = characterFrequency.characters;
frequency = characterFrequency.frequency;
printf("%s\n", characters);
//printf("%s\n", (char *) frequency);
//collect_character_distribution(buffer, lSize);
return 0;
}
我基本上想从结构函数返回多个值。首先,我在结构中定义它们,在函数步骤之后,我想从结构函数中获取字符数组和整数数组。
我测试了Struct Bar result
函数,它运行得很好。唯一的问题是collect_character_array
结构函数。
我得到分段错误错误。
我该如何解决问题?
答案 0 :(得分:1)
在您的函数中,您声明char *characters;
和int *frequency;
,它们是指针。然后在for_b
循环中索引这些数组。但是你从来没有为这些阵列分配空间。