简体   繁体   English

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

[英]How to correctly use pointers in my c program

So I turned in this code for my assignment to my teacher thinking I had completed his request that we use pointer techniques for writing our hangman assignment. 因此,我把代码分配给老师,以为我完成了他的要求,即我们使用指针技术编写for子手作业。 He gave it back and said I used array techniques and not pointer techniques. 他把它还给我,说我使用数组技术而不是指针技术。 I have struggled with learning pointers and arrays, so I am a bit confused how to fix where he said I went wrong. 我一直在努力学习指针和数组,所以我有点困惑如何解决他所说的错误。

These are the parts of my program he marked were array techniques and not pointer techniques: 这些是我标记为数组技术而非指针技术的程序部分:

*(q + i) = '*';

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

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

My full program code is below (can anyone help me understand how a proper pointer technique can be implemented, I clearly don't get it - THANKS in advance): 我的完整程序代码如下(任何人都可以帮助我了解如何实现适当的指针技术,我显然无法理解-提前感谢):

#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);
}

Original: 原版的:

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

Becomes: 成为:

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

A pointer is the base address, you can index it just like an array and the compiler will work out the offset according to the type declaration of the pointer. 指针是基地址,您可以像对数组一样对其进行索引,编译器将根据指针的类型声明计算出偏移量。

q = base address of your data, [i] indexes from the base address. q =数据的基地址,[i]从基地址开始索引。

I think I've interpreted your question wrong if you wanted to convert all the array references to pointers then: 如果您想将所有数组引用都转换为指针,那么我想我的解释是错误的:

Original: 原版的:

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

Becomes: 成为:

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

I can't quite see the point that is trying to be made, in C there is no difference in pointers and arrays they are the same and you can access them either way. 我不太明白要表达的观点,在C语言中,指针和数组没有区别,它们是相同的,您可以通过任何一种方式访问​​它们。

Lets recode your loop: 让我们重新编码循环:

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

Becomes: 成为:

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

First of all, p = &word; 首先, p = &word; and q = &guessed; q = &guessed; are incorrect; 不正确; remove the & in both cases. 在两种情况下都删除& word and guessed are arrays containing values of type char , which "decay" to pointers to their first items in most cases. wordguessed是包含char类型的值的数组,在大多数情况下,它们会“衰减”到指向其第一项的指针。

As an example of array decay, consider guessed : 作为数组衰减的一个例子,考虑一下guessed

Expression     Type
===========    ========
 guessed       char[20]
 guessed[0]    char
&guessed[0]    char *
  • guessed has type char[20] , or "array of 20 char values". guessed类型为char[20]或“ 20个char值的数组”。
  • guessed[0] has type char and is the same as *(guessed + 0) , ie 0 char s from the beginning of the array (which is the first item in the array). guessed[0]具有char类型,并且与*(guessed + 0) ,即从数组开头(数组的第一项)开始为0 char
  • &guessed[0] has type char * and is the same as &*(guessed + 0) . &guessed[0]类型为char * ,与&*(guessed + 0) Since & and * are inverse operations, they cancel each other out, resulting in &guessed[0] being the same as guessed + 0 —or just guessed . 由于&*是逆运算,因此它们彼此抵消,导致&guessed[0]guessed + 0相同-或只是guessed The only difference between guessed and &guessed[0] is the type because the [0] indexing operation happens before the & , causing the types to differ. guessed&guessed[0]之间的唯一区别是类型,因为[0]索引操作发生在&之前,导致类型不同。 Array decay effectively makes guessed the same as &guessed[0] in the context of your assignment to q , so you can write either one. 在分配给q的情况下,数组衰减有效地使guessed&guessed[0]相同,因此您可以写一个。

The exceptions where an array variable guessed will not behave the same as &guessed[0] are: guessed的数组变量与&guessed[0]行为不同的异常是:

  • sizeof(guessed) : gets the size of the entire array sizeof(guessed) :获取整个数组的大小
  • &guessed : gets a pointer to the array, with type char (*)[20] —pointer to array of 20 char values &guessed :获取类型为char (*)[20]的数组指针—指向20个char值的数组的指针

As for your teacher's instructions, you probably need to modify the p and q pointers themselves rather than use *(x + i) , which is the same as x[i] . 至于老师的指示,您可能需要修改pq指针本身,而不是使用*(x + i) ,这与x[i]相同。

For example: 例如:

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

becomes: 变成:

/* lines skipped */
for (q = guessed; *q != 0; q++)
{
    *q = '*';
}

Similarly: 类似地:

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

can be rewritten as: 可以重写为:

for (p = word, q = guessed; *p != 0; p++, q++)
{
    if (ch[0] == *p)
    {
        *q = ch[0];
        found = 1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM