2015-11-05 3 views
2

В настоящее время я работаю над проблемой для моего класса программирования C, и у меня есть проблема с моей программой. Мне удалось получить программу для компиляции, но функция отображения фактически не отображает содержимое списка так, как должно. Вот мой код:Связанный список не отображен как следует

/** 
* Create a structure that has one variable called value and one pointer to the list (making it a 
* linked list). Prompt for 5 values from the keyboard as input and store them in the linked list. Print 
* out the current contents of the list. Allow the user to add one more value to the linked list, and 
* print the contents of the list again. 
*/ 

#include <stdio.h> 

struct ValueStore 
{ 
    char value[100]; 
    struct ValueStore *nextItem; 
}; 
typedef struct ValueStore ValueStore; 

void display(ValueStore *); 

int main() 
{ 
    printf("This program will ask you for five words or phrases and store them in a list before repeating those integers back to you.\n"); 
    printf("You will then be able to add a final value (for a total of six) before the program repeats the list back to you and finishes.\n"); 

    /** 
    * Initialize the first five structs in the list. 
    */ 
    char inChar1[100]; 
    char inChar2[100]; 
    char inChar3[100]; 
    char inChar4[100]; 
    char inChar5[100]; 
    printf("Please enter a word or phrase: "); 
    gets(inChar1); 
    printf("Please enter a word or phrase: "); 
    gets(inChar2); 
    printf("Please enter a word or phrase: "); 
    gets(inChar3); 
    printf("Please enter a word or phrase: "); 
    gets(inChar4); 
    printf("Please enter a word or phrase: "); 
    gets(inChar5); 
    ValueStore fifth = { inChar5 }; 
    ValueStore fourth = { inChar4, &fifth }; 
    ValueStore third = { inChar3, &fourth }; 
    ValueStore second = { inChar2, &third }; 
    ValueStore first = { inChar1, &second }; 

    display(&first); //print out the list starting at first 

    /* 
    * add final item to list 
    */ 
    char inChar6[100]; 
    printf("Please enter a word or phrase: "); 
    gets(inChar6); 
    ValueStore sixth = { inChar6 }; 
    fifth.nextItem = &sixth; //link fifth and sixth together 

    display(&first); 
} 

void display(ValueStore *listStart) 
{ 
    while(listStart) 
    { 
     printf("%s\n", listStart->value); 
     listStart = listStart->nextItem; 
    } 
} 

При попытке запустить программу и ввести «привет», «мир», «что», «есть», и «вверх», чтобы ответить на экране моя функция дисплея подает на выход одиночная строка �p и переходит на следующий вход. Я ввожу последнюю строку (скажем, «привет»), и я снова получаю �p в терминале.

Я знаю, что gets() устарел в пользу fgets(), но мои инструкции явно использовать gets(), поэтому мои руки связаны там.

Мой GCC компилятор полностью в курсе

Using built-in specs. 
COLLECT_GCC=gcc 
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper 
Target: x86_64-linux-gnu 
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.2.1-22ubuntu2' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu 
Thread model: posix 
gcc version 5.2.1 20151010 (Ubuntu 5.2.1-22ubuntu2) 
+0

Могу ли я получить пример вывода? – LearningProcess

+0

Не используйте 'gets()' use 'fgets()' вместо этого. –

+0

Я сбив с толку, как вы его собрали. – TriHard8

ответ

1

В самом деле, компилятор дал вам много указаний (ака предупреждения) о проблеме в коде:

test41.c: In function ‘main’: 
test41.c:35: warning: initialization makes integer from pointer without a cast 
test41.c:36: warning: initialization makes integer from pointer without a cast 
test41.c:36: warning: initialization makes integer from pointer without a cast 
test41.c:37: warning: initialization makes integer from pointer without a cast 
test41.c:37: warning: initialization makes integer from pointer without a cast 
test41.c:38: warning: initialization makes integer from pointer without a cast 
test41.c:38: warning: initialization makes integer from pointer without a cast 
test41.c:39: warning: initialization makes integer from pointer without a cast 
test41.c:39: warning: initialization makes integer from pointer without a cast 
test41.c:49: warning: initialization makes integer from pointer without a cast 

Однако, этот код изменение будет работать.

#include <stdio.h> 
#include <string.h> 

struct ValueStore 
{ 
    char value[100]; 
    struct ValueStore *nextItem; 
}; 
typedef struct ValueStore ValueStore; 

void display(ValueStore *); 

int main() 
{ 
    printf("This program will ask you for five words or phrases and store them in a list before repeating those integers back to you.\n"); 
    printf("You will then be able to add a final value (for a total of six) before the program repeats the list back to you and finishes.\n"); 

    /** 
    * Initialize the first five structs in the list. 
    */ 
    char inChar1[100]; 
    char inChar2[100]; 
    char inChar3[100]; 
    char inChar4[100]; 
    char inChar5[100]; 
    printf("Please enter a word or phrase: "); 
    gets(inChar1); 
    printf("Please enter a word or phrase: "); 
    gets(inChar2); 
    printf("Please enter a word or phrase: "); 
    gets(inChar3); 
    printf("Please enter a word or phrase: "); 
    gets(inChar4); 
    printf("Please enter a word or phrase: "); 
    gets(inChar5); 
    ValueStore fifth; 
    strcpy(fifth.value, inChar5); 
    fifth.nextItem = NULL; 

    ValueStore fourth; 
    strcpy(fourth.value, inChar4); 
    fourth.nextItem = &fifth; 

    ValueStore third; 
    strcpy(third.value, inChar3); 
    third.nextItem = &fourth; 
    ValueStore second; 
    strcpy(second.value, inChar2); 
    second.nextItem = &third; 

    ValueStore first; 
    strcpy(first.value, inChar1); 
    first.nextItem = &second; 


    display(&first); //print out the list starting at first 

    /* 
    * add final item to list 
    */ 
    char inChar6[100]; 
    printf("Please enter a word or phrase: "); 
    gets(inChar6); 
    ValueStore sixth; 
    strcpy(sixth.value, inChar6); 
    sixth.nextItem = NULL; 
    fifth.nextItem = &sixth; //link fifth and sixth together 

    display(&first); 
} 

void display(ValueStore *listStart) 
{ 
    while(listStart) 
    { 
     printf("%s\n", listStart->value); 
     listStart = listStart->nextItem; 
    } 
} 

ВЫХОД: согласно вашему вопросу.

./a.out 
This program will ask you for five words or phrases and store them in a list before repeating those integers back to you. 
You will then be able to add a final value (for a total of six) before the program repeats the list back to you and finishes. 
Please enter a word or phrase: hello 
Please enter a word or phrase: world 
Please enter a word or phrase: what 
Please enter a word or phrase: is 
Please enter a word or phrase: up 
hello 
world 
what 
is 
up 
Please enter a word or phrase: to 
hello 
world 
what 
is 
up 
to 
+0

Поскольку это единственный реальный ответ, я собираюсь его принять. Однако Кайлум помог мне решить эту проблему. – firstofth300

Смежные вопросы