【发布时间】:2018-01-25 22:03:24
【问题描述】:
我正在尝试解决分配给我的任务中的一个问题 - 问题是我当前正在实现的功能之一不起作用。
首先,我被告知我的教授(下方)提供的代码不能以任何方式修改:
#include <crtdbg.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#define BLOCK_SIZE 64
typedef enum { FALSE = 0, TRUE } BOOL;
typedef struct {
char* fileName; // Frame fileName
}Frame, *pFrame, **ppFrame;
typedef struct {
unsigned int numFrames; // number of Frame*
ppFrame frames; // array of Frame*
}Animation, *pAnimation;
// Forward declarations
void initAnimation(pAnimation);
void insertFrame(pAnimation);
void deleteFrames(pAnimation);
void runFrames(pAnimation);
int main(void)
{
char response;
BOOL RUNNING = TRUE;
Animation A;
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
initAnimation(&A);
while (RUNNING)
{
printf("MENU\n 1. Insert a Frame\n 2. Delete all the Frames\n 3. Run the Animation\n 4. Quit\n");
scanf("%c", &response);
switch (response)
{
case '1':insertFrame(&A); break;
case '2':deleteFrames(&A); break;
case '3':runFrames(&A); break;
case '4':RUNNING = FALSE; deleteFrames(&A); break;
default:printf("Please enter a valid option\n");
}
printf("\n");
while ((response = getchar()) != '\n' && response != EOF);// clear input buffer
}
return 0;
}
接下来,我需要在提供的代码中为前向声明语句创建函数。我遇到问题的功能在这里:
void insertFrame(Animation *pAnimation)
{
char input[50];
int count;
int dupe = 0;
int blockFrames = pAnimation->numFrames % BLOCK_SIZE;
int blocks = (pAnimation->numFrames / BLOCK_SIZE) + 1;
printf("Insert a frame into the Animation\n");
scanf("%s", input);
/* check the input to see if it matches any of the existing frames */
for (count = 0; count < pAnimation->numFrames; count++)
{
printf("%s\n", pAnimation->frames[count]->fileName); /*test: show the file name to be compared against*/
if (strcmp(input, pAnimation->frames[count]->fileName) != 0)
{
dupe = 1;
printf("Dupe detected!");
return;
}
}
printf("dupe = %d\n", dupe);
/* afterwards, actually add the frame if it's ok */
if (dupe == 0)
{
pAnimation->numFrames++;
strcpy(pAnimation->frames[pAnimation->numFrames - 1]->fileName, input); /* <-- This is where the error happens */
}
}
每次我使用 printf 或 strcpy 显示或修改 pAnimation->frames[ ] 中的 fileName 结构成员时,都会显示读取访问冲突。经过仔细检查,pAnimation->frames[ ] 指向的地址中的文件名似乎是未知的。
为什么会发生这种情况,我该如何解决?
好的,所以在听取建议之后,我的 initAnimation 是这样的:
void initAnimation(Animation *pAnimation)
{
pAnimation->numFrames = 0;
pAnimation->frames = malloc(BLOCK_SIZE * sizeof(Frame));
}
我也联系了我的教授,他说我不需要分配任何东西,除非我“添加”一个新框架(通过 insertFrame)。我不完全确定他的意思。
【问题讨论】:
-
为什么说
strcpy()和printf()是宏? -
您的问题可能出在
initAnimation,您应该分配此空间并设置数组。 -
您将指针用作数组。它们不是一回事,尽管它们可以以类似的方式使用。您永远不会(至少在此代码中)为您尝试操作的数据结构分配内存,因此您会遇到访问冲突。另一方面,此代码是指针的噩梦。有更好的方法,虽然这可能只是一个学习练习。
-
你能把你的示例代码减少到一个仍然能说明问题的少量代码吗?