开发者

Print all List elements in C

i build this interface for List in c,i insert to the lis开发者_Python百科t pointer of array of struct, now i want to print all the fields of the struct,how can i do that?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef struct element {
    void *item;
    struct element *next;
} Element;

typedef Element* position;
typedef Element* List;

typedef struct strc   
{
    int row,col,value;
} Strc;

List initList()  
{
    Element *ls=malloc(sizeof(Element));
    if(ls)
        ls->next=NULL;
    else
        ls=NULL;
    return ls;
}

position insertToList(position p, void *item)  
{
    position newp=malloc(sizeof(Element));
    if(newp)
    {
        newp->next=p->next;
        p->next=newp;
        newp->item=item;
        //p=p->next;
    }
    else newp=NULL;
    return newp;
}

void *retriveFromList(position p)  {    return p->item;    }

position Next(position p)  {    return (position)p->next;    }

int isEmpty(List ls)  {    return ls->next==NULL;    }  

void freeList(List ls)  
{
    position pos=ls->next;
    while(ls->next!=NULL)
    {
        pos=ls->next;
        ls->next=pos->next;
        free(pos);
    }
}
void puts(List *ls)
{
    Position p=*ls;
    Strc *tmp;
    int i;
    for(i=0;i<10;i++)
    {
        tmp=(Strc *)malloc(sizeof(strc));
        tmp->row=i;
        tmp->col=i+1;
        tmp->value=i+2;
        p=insertToList(p,tmp);
    }
}
void print_list(List ls)  
{
    position p=ls->next;
    while(p!=NULL)
    {
        printf("%3d\n",*((int*) retriveFromList(p)));
        p=Next(p);          
    }
}

void main()
{
    List ls=initList();
    puts(&ls);
    print(ls);
}


So, my C isn't grand

But, it seems like there are a ton of little typos that are going to eat you as you get this to run. One of the biggest being that puts() is already defined in stdio.h.

First, this thing doesn't compile for me, so working through all the compiler errors got me pretty far. Your puts function also was missing a closing bracket. I renamed it to putv() and changed it to be the following.

void putv(List *ls)
{
  position p=*ls;
  Strc *tmp;
  int i;
  for(i=0;i<10;i++)
    {
      if(tmp=(Strc *)malloc(sizeof(Strc)))
        { 
          tmp->row=i;
          tmp->col=i+1;
          tmp->value=i+2;
          p=insertToList(p,tmp);
        }
    }
}

The second issue was that your main function was not calling print_list(), but instead calling plain print().

void main()
{
  List ls=initList();
  putv(&ls);
  print_list(ls);
}

This doesn't solve all of your problems

Mostly because I don't think it's printing what you want, but I'm going to leave a little bit for you to figure out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜