C 如何引用一个数组中的不同内存位置

标签 c arrays pointers

我正在读取一个文件并将每个字符添加到一个数组中。然后,我通过删除空格和其他非必要字符将这些字符分解为单词。现在,要单独处理每个单词,我想将每个单词添加到它自己的数组中。有什么办法吗?我试图添加每个单词开头的内存位置,但它一直给我数组开头的内存地址。问题是,在下面的代码中,名为“buffer”的变量在 while 循环的每次迭代中都会用一个新词覆盖自身。我需要能够引用每个单词,以便将其推送到链表中。这是我到目前为止所拥有的:

#include <stdio.h>
#include <ctype.h>

int main(int argc, char **argv) {
char buffer[1024];
int c;
size_t n = 0;

FILE *pFile = stdin;

pFile = fopen(argv[1], "r");
if (pFile == NULL) perror("Error opening file");
    else {
        while(( c = fgetc(pFile)) != EOF ) {

            if (isspace(c) || ispunct(c)) {

                if (n > 0) {
                    buffer[n] = 0;
                    printf("read word %s\n", buffer);
                    n = 0;
                }
            } else {
                buffer[n++] = c;
            }
        }
        if (n > 0) {
            buffer[n] = 0;
            printf("read word %s\n", buffer);
        }
        fclose(pFile);
    }
return 0;
}

如果我给出一个包含字符“This is a test document that holds words for this exercise”的文件,则会生成以下内容:

read word This
read word is
read word a
read word test
read word document
read word that
read word holds
read word words
read word for
read word this
read word exercise

最佳答案

看来您的开端不错。您正在做的是一次一个地成功地将所有单词读取到一个数组中,然后每次都覆盖它们。

The problem is, in the code below, the variable named 'buffer' overwrites itself with a new word with each iteration of the while loop.

当然可以:

     if (n > 0) {
           buffer[n] = 0; // this line terminates each string
           printf("read word %s\n", buffer);
           n = 0;         // this line resets the array so you overwrite with the next
                          // word
     }

所以此时你只需要将这些单词放入你的链表中而不是覆盖它们。您可以将它们全部存储在数组中(如果它足够长),但是当您只需要将它们取回时为什么还要费心呢?此时你真正需要做的是替换这一行:

printf("read word %s\n", buffer);

使用代码将单词添加到您的链接列表中。基本上你需要某种“节点”结构,在最基本的意义上你需要做类似的事情:

struct node{
   char * word;       // place to add the word
   struct node *next; // pointer to the next node
};

你只需要为每个节点和节点中的每个字符串获取一些内存,下面的代码假设你有一个头节点指向链表中的第一个节点,并且你有一个指针指向从头开始的当前节点:

cur->next = malloc(sizeof(node));          // assign memory for a new node
cur = cur->next;                           // move current to the next node
cur->word = malloc(sizeof strlen(buffer)); // assign memory for the word
cur->next = NULL;                          // set the next pointer to NULL
strcpy(cur->word, buffer);                 // copy the word from the buffer 
                                           //   to your list

关于C 如何引用一个数组中的不同内存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15717876/

相关文章:

c - C:为什么C需要char的内存地址才能将其转换为int?

c - 在 Clang 中使用带有 qsort 的 block 时出现不兼容的指针类型错误

c - 释放具有结构节点的链表结构

找不到发生段错误的位置

php - 检查数组键是否存在,不区分大小写

javascript - 按标签重构嵌套 JSON 数据 - Javascript

c - 离开函数后值消失

c - 静态字符数组的含义?

c++ - 这些类型的指针之间有什么区别?

c++ - 访问冲突写入位置 0x00000000。指针问题