gpt4 book ai didi

c - 如何在我的 C 程序中正确使用指针

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:29 24 4
gpt4 key购买 nike

因此,我将这段代码交给了我的老师,认为我已经完成了他的要求,即我们使用指针技术来编写刽子手作业。他还给我说我使用了数组技术而不是指针技术。我一直在努力学习指针和数组,所以我有点困惑如何修复他说我出错的地方。

这些是我程序中他标记为数组技术而非指针技术的部分:

*(q + i) = '*';

if (ch[0] == *(p + i))

*(q + i) = ch[0];

我的完整程序代码如下(任何人都可以帮助我理解如何实现正确的指针技术,我显然不明白 - 提前感谢):

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

void Instructions();
void PlayGame();
void PrintToLog(char *word);

int main()
{

Instructions();
PlayGame();

return 0;
getchar();
}

void Instructions()
{
printf("This is a game of hangman. Attempt to guess secret word\n");
printf("by entering a letter from a to z. The game is over once you\n");
printf("have entered 8 incorrect guesses.\n\n");
}

void PlayGame()
{
char word[] = { "hello" };
char guessed[20];
int i, incorrect_count, found;
char ch[2];
char *p, *q;

p = &word;
q = &guessed;
strcpy(guessed, word);

PrintToLog(word);

for (i = 0; i < strlen(guessed); i++)
{
*(q + i) = '*';
}
incorrect_count = 0;

while (incorrect_count < 8 && strcmp(guessed, word) != 0)
{
for (i = 0; i < strlen(guessed); i++)
printf("%c ", guessed[i]);
printf("\n");
printf("Enter your guess:");
gets(ch);
found = 0;
for (i = 0; i < strlen(word); i++){
if (ch[0] == *(p + i))
{
*(q + i) = ch[0];
found = 1;
}
}
if (found == 0)
incorrect_count++;
}

if (incorrect_count < 8)
{
printf("\nThe word is %s. You win!", word);
getchar();
}
else
{
printf("\nThe correct word is %s. You lose!", word);
getchar();
}

return 0;
}

void PrintToLog(char *word)
{
FILE *pOutput;

pOutput = fopen("MyLogFile.txt", "w+");
if (!pOutput) return;
fprintf(pOutput, "Start of game\n");
fprintf(pOutput, "This is the word player is trying to guess: %s\n", word);

fclose(pOutput);
}

最佳答案

原文:

    *(q + i) = '*';
if (ch[0] == *(p + i))
*(q + i) = ch[0];

变成:

    q[i] = '*';
if (ch[0] == p[i]))
q[i] = ch[0];

指针是基地址,你可以像数组一样对其进行索引,编译器会根据指针的类型声明计算出偏移量。

q = 数据的基地址,[i] 从基地址开始索引。

如果您想将所有数组引用转换为指针,那么我想我解释错了您的问题:

原文:

    *(q + i) = '*';
if (ch[0] == *(p + i))
*(q + i) = ch[0];

变成:

    *(q + i) = '*';
if (*ch == *(p + i)))
*(q + i) = *ch;

我不太明白要表达的意思,在 C 中,指针和数组没有区别,它们是相同的,您可以通过任何一种方式访问​​它们。

让我们重新编写您的循环:

    for (i = 0; i < strlen(word); i++){
if (ch[0] == *(p + i))
{
*(q + i) = ch[0];
found = 1;
}
}

变成:

    for( p=word; *p!='\0'; p++ ) {
if ( *ch == *p ) {
*p = *ch;
found = 1;
break;
}
}

关于c - 如何在我的 C 程序中正确使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647420/

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