【发布时间】:2014-01-10 22:19:11
【问题描述】:
我遇到了一个编程问题,我必须添加数组的前两个索引,然后它们的总和必须在第一个位置(删除添加的两个节点),这肯定会导致前移休息数组的一个索引位置。 但问题是它的转变非常奇怪。 请仔细看,我只需要使用数组,没有其他数据结构 这是我想要的清晰图片。看例子:
arr[5]= {1,2,3,4,5}
First execution:
{3,3,4,5} //here we added first two elements (1+2=3)
second execution:
(6,4,5) //again added first two elements
third execution:
{10,5}
finally:
{15}
我的代码是:
Node *temp;
Node *array[5]; //actually this array is declared like this {1,2,3,4,5}
int i;
for (i=0;i<5;i++)
{
array[i] = malloc(sizeof(Node));
array[i]->value = freq[i+1];//this contains {1,2,3,4,5}
array[i]->sym = arry[i];
array[i]->left = NULL;
array[i]->right = NULL;
printf("%d ",array[i]->value );
}
int j=0,d,t=5;
while (t>1 )
{
temp = array[j];
printf(" \ncheckOne %d ",array[j]->value);
printf("checkTwo %d \n",array[j+1]->value );
array[j]->value= temp->value + array[j+1]->value; //
printf(" checkSumOfOneAndTwo %d \n",temp->value);
array[j]=array[j+1];
array[j]->left=array[j+1];
array[j]->right=temp;
array[j]=temp;
for(d=0;d < t;d++)
printf(" %d ",array[d]->value);
t--;
j++;
}
它的输出是:
The Frequencies corresponding to alphabets in Input.txt files are as follows
: a b c d e
1 2 3 4 5
checkOne 1 checkTwo 2
checkSumOfOneAndTwo 3
3 2 3 4 5
checkOne 2 checkTwo 3
checkSumOfOneAndTwo 5
3 5 3 4
checkOne 3 checkTwo 4
checkSumOfOneAndTwo 7
3 5 7
checkOne 4 checkTwo 5
checkSumOfOneAndTwo 9
3 5
我是编程初学者。谁能告诉我错误是什么以及如何解决? (我有义务只使用数组来实现它,所以没有链表、堆等)
【问题讨论】:
-
array[j]->value= temp->value + array[j+1]->value;j+1 --> 5 , 数组越界 -
@BLUEPIXY 那么它的解决方案是什么?请查看我与此输入对应的输出,有什么办法可以解决?谢谢
-
将数组作为栈处理会很容易。
-
但是怎么做呢?任何对我有帮助的代码,但我只需要处理数组。谢谢你解释我。
标签: c arrays segmentation-fault huffman-code