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

标签 c arrays pointers

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

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

*(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/

相关文章:

javascript - 遍历数组只显示最后一个值

c++ - 错误: ‘void*’ is not a pointer-to-object type

C 类型系统中的兼容类型和忽略顶级限定符

c++ - CreateFile 失败,错误代码 2,而文件存在

javascript - 将数组的引用存储在数组中

我可以通过指针从另一个文件访问一个文件的静态变量吗?

c++ - 值调用和指针引用调用

c - 如果相同的计数变量 'i' 在每个嵌套的 for 循环中被视为不同,那么为什么在内部循环中对它的更改会持续到外部?

c++ - 如何从C调用C++函数?

比较数组的 C 单元测试框架