gpt4 book ai didi

c - RUN FAILED 退出值 5 尝试交换数组

转载 作者:行者123 更新时间:2023-11-30 17:25:40 24 4
gpt4 key购买 nike

/*Jeremy Johnson  11-18-48
*
*The purpose of this program to to swap halves of an array. So {1 2 3 4 5 6}
*becomes {4 5 6 1 2 3} using pointer notation.
*/

#include <stdio.h>
#include <string.h>

int array[] = {1, 2, 3, 4, 5, 6}; //initialize array
void mirror(int* array, int from_index, int to_index); //prototype statment

int main() {
//define and assign pointer to array address
int *arrptr, i;
arrptr = &array[0];

//print original array
printf("Original Array: \n");
for (i = 0; i <= 5; i++) {
printf("%d", array[i]);
}
printf("\n");

//call function to swap values and mirror the array
mirror(arrptr, 0, 2);
mirror(arrptr, 3, 5);
mirror(arrptr, 0, 5);
mirror(arrptr, 1, 4);
mirror(arrptr, 2, 3);

//print final array
printf("Mirror Array: \n");
for (i = 0; i <= 5; i++) {
printf("%d", array[i]);
}
printf("\n");

return 0;
}

void mirror(int* array, int from_index, int to_index) {
//create pointer for temporary memory storage
int *temp, c[1];
temp = &c[0];

//Place to_index in temporary memory
*(temp) = *(array + to_index-1);
//Copy from_index to to_index
*(array + to_index-1) = *(array + from_index-1);
//Copy temporary value back into from_index
*(array + from_index-1) = *(temp);

return;
}

/* This code works for the function however I am not allowed to use array
notation.

c[1]=array[to_index];
array[to_index]=array[from_index];
array[from_index]=c[1]; */

我正在尝试交换数组的每一半;我通过调用镜像函数 5 次并交换适当的值来切换数组的索引。我能够使用底部的注释代码代替当前的函数代码来执行此操作,但现在我收到并退出值 5,我不确定为什么。 (我在代码中没有收到其他错误)

最佳答案

// perhaps swap the array by:

void mirror( int*, int* );

int main()
{
...
int *pSecondHalf = array[(sizeof(array)/sizeof(int))>>1];
// note: above line will not work for odd size array so:
if( array[(sizeof(array)/sizeof(int)] & 0x01 )
{
pSecondHalf++; // middle term in odd size array will not move
}

int *pFirstHalf = array;

const int *pLastHalf = array+((sizeof(array)/sizeof(int))>>1);

// note: following 'for' loop will execute one extra time
// for odd size array, but nothing will be changed

for( ; pFirstHalf < pLastHalf; pFirstHalf++, pSecondHalf++ )
{
mirror( pFirstHalf, pSecondHalf );
}
...
return(0);
}

// and in mirror()

void mirror( int *pVal1, int* pVal2)
{
int temp = *pVal1;
*pVal1 = *pVal2;
*pVal2 = temp;
}

关于c - RUN FAILED 退出值 5 尝试交换数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006679/

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