首页 > 解决方案 > 如何在使用结构的同时将字符串从数组传递给指针(在c中)

问题描述

这段代码的重点是从用户那里读取一个字符串(少于 50 个字符),然后使用 letters 函数将字符串的字母放入指针中,这样每个字母只会出现一次,然后还计算每个字母的出现次数。最后,使用报告功能,它应该在屏幕上输出我刚刚解释的所有内容。例如,用户输入“Hello”程序输出:

H : 1    
e : 1    
l : 2   
o : 1    

编码:

#include <stdio.h>
#include <stdlib.h>
#include <string.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;
    for(i=0; name[i]!='\0'; i++){
        //everything is done here
    }
    return;
}

void report(ListofChar chars) {
    int i;
    // this is only to output the results
    return;
}

提前致谢

标签: carraysstringpointersstructure

解决方案


根据我的理解,您想使用单链表将节点连接在一起。在示例程序中,我在开头添加了新节点。头指针保存最后添加的节点的地址。

#include <stdio.h>
#include <stdlib.h>
#include <string.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, ListofChar * head_ptr);

int main() {
 char name[50];
 ListofChar chars = NULL;
 scanf("%s", name);
 letters(name, &chars);
 report(chars);
 return 0;
}

Char * createnode(char ch,ListofChar * head_ptr ) {
  CharNode_ptr newnode_ptr;
  ListofChar  temp;
  temp = *head_ptr;
  while(temp) {
     if( temp->ch  == ch) {
     temp->occurs += 1;
     return;
     }
     temp= temp->next;
 }
 newnode_ptr = malloc(sizeof (Char));
 newnode_ptr -> ch = ch;
 newnode_ptr -> occurs = 1;
 newnode_ptr -> next = *head_ptr;
  *head_ptr = newnode_ptr;
  return newnode_ptr;
 }

void letters(char name[50], ListofChar * lst_ptr) {
  int i;
  for(i=0; name[i]!='\0'; i++){
     createnode(name[i],lst_ptr);
     //everything is done here
   }
 return;
  }

 void report(ListofChar chars) {
    int i;
    while(chars)
     {
   printf("%c %d \n",chars->ch,chars->occurs);
   chars = chars->next;
    }
   //printf("%c \n",chars->ch);
   // this is only to output the results
   return;
   }

推荐阅读