gpt4 book ai didi

c - 尝试更改短程序以使用指针

转载 作者:行者123 更新时间:2023-11-30 15:22:51 25 4
gpt4 key购买 nike

这周我刚刚开始学习指针,但我在完成实验作业时遇到了麻烦。我得到了程序,必须更改它以使用旧变量和新变量的指针。 (代码链接在本文底部)

我已经尝试过了,但我很困惑并且遇到了一些问题:

1) 我的值没有输入到正确的索引中。

2) 当我尝试添加第三个值时出现段错误。我知道当我尝试访问我无权访问的内存时会发生这种情况,因此我的指针在某个地方出错了。

任何形式的指导将不胜感激!

原始工作代码:

#include <stdio.h>
#define ARSZ 10

typedef unsigned int UINT;

void showData(int [], UINT, UINT, int, int);

int main(void){

int array[ARSZ] = {0};
UINT old = ARSZ-1, new = ARSZ-1;
int runningTot = 0, maxAveLen, curAveLen = 1, newVal, numCtr=0;

printf("Enter the maximum number of values to average over: ");
scanf("%d", &maxAveLen);

while(1){

runningTot -= array[old]; // subtract value pointed to by old
old += ((++numCtr) >= maxAveLen); // increment old if maxAveLen inputs
old %= ARSZ; // wraps old to 0 if array sz exceeded

printf("Enter new value to array:"); // get new value to add to array
scanf("%d", &newVal);

new = (++new)%ARSZ; // increment new reset to 0 if >= ARSZ
runningTot += (array[new] = newVal); // add new Value at [new] location

// Determine the number of values to average over i.e. 1,2,3,4,4,4,4,4...
curAveLen = (numCtr >= maxAveLen)?maxAveLen:numCtr;
showData(array, old, new, runningTot, curAveLen);

}
}

// Display the current data
void showData(int ar[], UINT O, UINT N, int RT, int aveLen){

for (int i=0; i < ARSZ; i++) // Print out the array contents
printf("%d\t", ar[i]);

printf("\nOld = %u, \tNew = %u, \tTotal = %d, \tAve = %5.2f\n\n",
O, N, RT, (float)RT/aveLen);

}

我的损坏代码:

#include <stdio.h>
#define ARSZ 10

typedef unsigned int UINT;

void showData(int [], UINT*, UINT*, int, int);

int main(void){

int array[ARSZ] = {0};
UINT *old = &array[ARSZ-1], *new = &array[ARSZ-1];
int runningTot = 0, maxAveLen, curAveLen = 1, newVal, numCtr=0;

printf("Enter the maximum number of values to average over: ");
scanf("%d", &maxAveLen);

while(1){

runningTot -= array[*old];
*old += ((++numCtr) >= maxAveLen);
*old %= ARSZ;

printf("Enter new value to array:");
scanf("%d", &newVal);

*new = *(++new)%ARSZ; // Error might be occurring here
runningTot += (array[*new] = newVal);

curAveLen = (numCtr >= maxAveLen)?maxAveLen:numCtr;
showData(array, old, new, runningTot, curAveLen);

}
}

// Display the current data
void showData(int ar[], UINT *O, UINT *N, int RT, int aveLen){

for (int i=0; i < ARSZ; i++)
printf("%d\t", ar[i]);
printf("\nOld = %u, \tNew = %u, \tTotal = %d, \tAve = %5.2f\n\n",
*O, *N, RT, (float)RT/aveLen);

}

最佳答案

这些并不等同

UINT *旧 = &array[ARSZ-1], *新 = &array[ARSZ-1];//...但仅初始化指针

UINT 旧 = ARSZ-1,新 = ARSZ-1;//...但仅初始化指针

您不能创建指向常量的指针。您可以做的是使用 malloc() 或为其分配地址来为“旧”和"new"分配内存另一个有效的 UINT。然后你可以分配一个常量。

这也是错误的:*new = *(++new)%ARSZ;//如果 >= ARSZ 则将新重置增加到 0 您正在递增指针本身而不是指针内的值。试试这个:

*new = (++*new)%ARSZ;

关于c - 尝试更改短程序以使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026993/

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