ファイル名を先頭の位置にリストに入力する方法を実装しようとしています。リストに最初のエントリがあると、関数insert内の2回目の実行で別のファイル名を入力しますが、今回は次の(pNext)位置に入力します。Cリンクリストの条件文
私は紙の上でそれを行う方法について考えていますが、その実装は私を混乱させます。私は最初にファイル名を渡すことができます。しかし、2番目の試行では条件を作成しました:if(frame-> pNext!= NULL){// // pnext位置に追加する必要があります
しかし、この条件は常に最初のフレームを挿入する前に実行されます。 frame-> pNextはNULLですが、私はmallocを使用して以来、ガベージメモリを指しているため、条件は常に真ですが、最初の実行時にはfalseにする必要があります。
このようにして、先頭にリストを追加し、次に実行すると、2番目のファイル名が追加されます。
例:ファイル名:[最初] [二] [三]
#include <crtdbg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
typedef enum { FALSE = 0, TRUE } BOOL;
struct Frame {
char* fileName;
struct Frame* pNext;
};
struct Animation {
struct Frame* frames;
};
// Forward declarations
void initAnimation(struct Animation*);
void insertFrame(struct Animation*);
void runFrames(struct Animation*);
int main(void)
{
char response;
BOOL RUNNING = TRUE;
struct 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 '3':runFrames(&A); break;
case '4':RUNNING = FALSE; break;
default:printf("Please enter a valid option\n");
}
printf("\n");
while ((response = getchar()) != '\n' && response != EOF);// clear input buffer
}
return 0;
}
void initAnimation(struct Animation* pA) {
pA = NULL;
}
void insertFrame(struct Animation* pA) {
char* fileName;
struct Frame* frame;
fileName = (char *)malloc(sizeof(char)); //filename
frame = (struct Frame *)malloc(sizeof(struct Frame)); //next frame
frame->fileName = (struct Frame *)malloc(sizeof(struct Frame)); //filename
frame->pNext = (struct Frame *)malloc(sizeof(struct Frame)); //for next frames
printf("Insert a Frame in the Animation\n");
printf("Please enter the Frame filename :");
scanf("%s", fileName);
strcpy(frame->fileName, fileName); //store into filename
if (frame->pNext != NULL) { //add to pnext frame
printf("next frames");
frame->pNext = frame;
}
else { //add to first frame once
printf("this is the first frame");
pA->frames = frame;
}
}
このコードの大部分は間違いありません。私がすぐに言うことができるのは、4つの 'malloc'の実行が非常に疑わしいことだけです。おそらく2つしか必要ではないでしょうし、確かにそのうちの1つを1バイトにしたくないでしょう。 –
@DavisHerringただ1バイトで何を意味していますか? –
'sizeof(char)'は1になるように定義されています。 –