c - 访问函数中的链表 - C

标签 c pointers linked-list

我的问题是我想访问我在 letters 函数中创建的链接列表,并使用它在 report 函数中将其打印出来。然而,我似乎无法做到这一点,当我尝试检查 charslst_ptr 的内存地址时,我发现它们彼此不同。为了实现我的目标,它们不应该是相同的吗?
提前致谢!!!

#include <stdio.h>
#include <stdlib.h>
struct charact {
   char ch;
   int occurs;
   struct charact *next;
};
typedef struct charact Char;

typedef Char * ListofChar;

typedef Char * CharNode_ptr;

void letters(char name[50], ListofChar * chars_ptr);

void report(ListofChar  chars);

Char * createnode(char ch);

int main() {
    char name[50];
    ListofChar chars = NULL;
    scanf("%s", name);
    letters(name, &chars);
    report(chars);
    return 0;
}
Char * createnode(char ch) {
    CharNode_ptr newnode_ptr ;
    newnode_ptr = malloc(sizeof (Char));
    newnode_ptr -> ch = ch;
    newnode_ptr -> occurs = 0;
    newnode_ptr -> next = NULL;
    return newnode_ptr;
}
void letters(char name[50], ListofChar * lst_ptr) {
    int i,j,occs;
    lst_ptr=malloc(100);
    for(i=0;i<strlen(name);i++){
        occs=0;
        for(j=0;j<strlen(name);j++){
            if(name[i]==name[j]){
                occs++;
            }
        }
        lst_ptr[i]=createnode(name[i]);
        lst_ptr[i]->occurs=occs;
        if(i>0){
            lst_ptr[i-1]->next=lst_ptr[i];
        }
    }
    printf("%p\n",lst_ptr);
    return;
}
void report(ListofChar  chars) {
    printf("%p",chars);
return;
}

最佳答案

您刚刚发现了使用指针是什么感觉:)

所以首先,不要使用 typedef 名称中不包含星号的指针类型;否则可读性会受到影响。事实上,由于这个原因,我一开始很难遵循你的代码。

出于上述原因,在这个答案中,我将假装 typedef Char * ListofChartypedef Char * CharNode_ptr 不存在,而仅使用 Char 相反。

在您的 main 函数中,您有以下声明:

Char* chars = NULL;

您需要记住的是指针chars本身有一个内存地址。然而,chars 指向 NULL

现在,在您的 letters 函数中,您需要修改 chars 指向的内容。您可以通过两种方式实现此目的:通过像这样直接从函数内引用它

void letters(char name[50]) {
    /* ... */

    chars = malloc(100);

    /* ... */
}

或者通过将 char 的地址传递给 letters,从而使 letters 能够修改 chars 所指向的内容至

void letters(char name[50], Char** lst_ptr) {
    /* ... */

    // Note that I'm referring to what lst_ptr is pointing to,
    // that is, chars. At this point of the code, *lst_ptr == chars
    *lst_ptr = malloc(100);

    /* ... */
}

现在看看函数reportletters 的签名。前者仅采用指针 (Char*),后者采用指向指针的指针 (Char**)。这就是为什么你的 printf 会在内存中给你不同的位置。 report 中的 printf 正在打印 chars 所指向的内容;而letters中的printf正在打印chars的地址(由lst_ptr保存)。

为了打印相同的地址,请打印lst_ptr指向的内容,即:

printf("%p\n", *lst_ptr);

我采用了您发布的代码并应用了我刚才所说的内容,这是我机器上的输出

gianluca
0x55b67d7db6e0
0x55b67d7db6e0

关于c - 访问函数中的链表 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50200405/

相关文章:

c - 使用指针而不是索引更新数组

java - 将文件内容复制到链表数组中并对其进行排序

java - Java中LinkedList中间插入

c - 在 nesC 中将结构体深度复制到结构体数组(类似于 C)

c - 在 C 中使用 malloc 为 typedef 类型分配空间

c - 在 C 中获取未定义或实现定义行为的无效指针的值?

c++ - 为链表类型数据结构实现 "deleting algorithm"

在c中捕获网络数据包

需要克里昂的帮助

c++ - 指向基类的指针在 while 循环中丢失,导致段错误。 C++