C - 从函数获取正确的指针并通过另一个函数打印

时间:2015-02-15 15:03:54

标签: c pointers

我将pointer指向正确的"框",但是使用number通过第二个{{1}打印linked list我遇到了一些麻烦}}。我不会复制我的整个代码,因为它会有点作弊,我的观点是要学习。所以我会写一个我想做的简单例子......

function

现在,如果我想访问&#34;框&#34;例如,创建另一个打印typedef struct{ int number; struct node *next; } mystruct; void main() { char numb[1000]; scanf("%s",numb); mystruct *head=malloc(sizeof(mystruct)); CreateList(numb, &head); PrintList(head); } CreateList(char x[1000],mystruct **head) { int i; int digits=strlen(x) for (i=0;i<digits;i++) { // creating the linked list. meaning each digit of number going into a "box" } } 的函数。

显示示例:

12345 numb

12345

1 个答案:

答案 0 :(得分:0)

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

typedef struct node {
    int number;
    struct node *next;
} mystruct;

void CreateList(char x[1000], mystruct **head);
void PrintList(mystruct *head);
void FreeList(mystruct *head);

int main(void){
    char numb[1000];

    scanf("%999s", numb);
    mystruct *head;

    CreateList(numb, &head);
    PrintList(head);
    FreeList(head);
    return 0;
}

void CreateList(char x[1000], mystruct **head){
    mystruct *currNode, *newNode;
    *head = NULL;
    int i;
    for (i=0;x[i];i++){//x[i] != '\0'
        if(NULL == (newNode = malloc(sizeof(*newNode)))){
            perror("error of malloc");
            exit(EXIT_FAILURE);
        }
        if(i==0){
            *head = currNode = newNode;
        }
        newNode->number = x[i];//x[i] - '0'
        newNode->next = NULL;
        currNode = currNode->next = newNode;
    }
}
void PrintList(mystruct *head){
    while(head){
        printf("%c", head->number);//%d
        head = head->next;
    }
    putchar('\n');
}
void FreeList(mystruct *head){
    while(head){
        mystruct *temp = head;
        head = head->next;
        free(temp);
    }
}