我在Recursion部分阅读'ANSI-C编程语言'。我正在运行递归示例:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
static int v[] = {1,3,6,1,2,3,6,89,3,5,7,2,3};
int size = sizeof(v)/sizeof(v[0]);
void sy_swap (int v[], int i, int j);
void sy_qsort(int v[], int left, int right);
/*Swap function*/
void sy_swap (int v[], int i, int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
/*Sort function*/
void sy_qsort(int v[], int left, int right)
{
int i, last;
static int loop = 0;
if(left >= right){ /*Finish sort*/
return;
}
sy_swap(v, left, (left + right)/2); /*Move middle element to beginning of the half*/
last = left;
for(i = left+1; i<=right; i++){ /*After this loop, we have to half: smaller than 'middle element' and bigger*/
if (v[i] < v[left]){
sy_swap(v, ++last, i);
}
}
sy_swap(v, left, last); /*Move 'middle element' to the head of SMALL half, to finish division the array into 2 half*/
sy_qsort(v,left, last-1); /*Sort Small Half*/
sy_qsort(v, last+1, right); /*Sort Big Half*/
}
int main(void)
{
int i = 0;
printf("sizes: size of v=%d, size of v[0]=%d, total elements=%d\n",(int)sizeof(v), (int)sizeof(v[0]),size); /*Check 'size' before sort*/
sy_qsort(v,0,size);
printf("sizes: size of v=%d, size of v[0]=%d, total elements=%d\n",(int)sizeof(v), (int)sizeof(v[0]),size); /*Check 'size' after sort*/
for (i =0; i<size; i++){
printf("%d,",v[i]);
}
return (0);
}
有人知道为什么'size'变量在调用sort函数后被改变了,尽管sort函数中没有操作改变'right'参数?
这是结果显示'size'从实际的13(数组中的元素总数)更改为89(数组中的最大元素)
sizes: size of v=52, size of v[0]=4, total elements=13
sizes: size of v=52, size of v[0]=4, total **elements=89**
1,1,2,2,3,3,3,3,5,6,6,7,13,89,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0......
答案 0 :(得分:3)
您有未定义的行为,因为您将数组的size
包含为有效索引,而不是。
以循环
为例for(i = left+1; i<=right; i++)
在sy_qsort
函数的第一次main
调用中,变量right
等于size
,这是数组的大小,但作为索引是超越的最后一个元素。条件必须是i < right
。