这段代码的要点是从用户那里读取一个字符串(小于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;
}
关于c - 如何将字符串从数组传递到指针,同时也使用结构(在 c 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50325993/