c - 如何在使用结构的同时将字符串从数组传递给指针(在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;
}
提前致谢
解决方案
根据我的理解,您想使用单链表将节点连接在一起。在示例程序中,我在开头添加了新节点。头指针保存最后添加的节点的地址。
#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;
}
推荐阅读
- java - 我有一个方法 compute(int months) 但它不会像我想要的那样迭代
- caching - Solr 构面结果在每个查询上都不同
- python-3.x - python - 如何在python中找到用户与用户相似度的皮尔逊相关系数?
- networking - 在 Ubuntu 中分配静态 IP 地址
- autocomplete - 散景的自动完成输入无法正常工作
- javascript - jquery替换字符并开始和结束
- android - 使用 .setDataSource 从当前正在播放的音乐应用中获取 mediaMetadata
- python - 构建一个没有重复集合的集合元组
- c - 为 Teensy Atmega 32u4 实施 PI 控制
- javascript - 网站导航在 WKWebview 中不起作用