'Not getting the wanted output in project with structs
Given Code:
#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(void)
{
char name[50];
ListofChar chars = NULL;
scanf("%49s", 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)
{
/* add your code */
return;
}
void report(ListofChar chars)
{
/* add your code */
return;
}
My code:
#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,int length);
void distance(char name[50],size_t size,Char *chars);
Char * createnode(char ch);
int main(void)
{
char name[50];
ListofChar chars = NULL;
scanf("%49s", name);
letters(name, &chars);
report(chars,strlen(name));
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)
{
/* add your code */
size_t i, j;
j = strlen(name);
memset(lst_ptr, 0, 50*sizeof (Char));
for(i = 0; i < j; i++){
distance(name, i, *lst_ptr);
}
return;
}
void report(ListofChar chars,int length)
{
int i;
for(i = 0; i < length; i++){
printf("\n%c: %d", chars[i].ch, chars[i].occurs);
}
/* add your code */
return;
}
void distance(char name[50],size_t size,Char *chars)
{
int i,length;
length = strlen(name);
chars -> ch = name[size];
for (i=size+1; i<length; i++)
{
if(name[i] == chars -> ch)
{
chars-> occurs = i - size;
return;
}
}
chars ->occurs=0;
return;
}
I want this program to print the distance from the next repeated letter. For example: testing t:3 e:0 s:0 t:0 i:0 n:0 g:0
Instead i get no output.Im new to C programming and im pretty average,this is a Uni project.I believe that the createnode function will be used in later versions of the project but im not sure.Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
