[英]How to implement an array within a linked list in C
我可以存儲一切。 但是在鏈表中實現數組時遇到了問題。 該Baratok應該保留數字值,直到輸入為-1。 但是當我嘗試打印它時,它只給我-1。 那么什么是適當的實現呢?
我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getl(char s[], int lim)
{
int c,i;
for(i = 0; i < lim && (c = getchar()) != '\n' && c!=EOF; i++)
s[i] = c;
s[i] = '\0';
while(c != '\n' && c!=EOF)
c=getchar();
return i;
}
struct szemelylista {
int szemelyId;
char nev[50];
int *baratok;
struct szemelylista *kov;
} ;
int main()
{
struct szemelylista *llist = NULL, *elozo, *horgony;
int ct = 0, barat, i;
char s[50];
horgony = elozo = NULL;
while(printf("Name: ") && getl(s, 50))
{
if(!(llist = (struct szemelylista*)malloc(sizeof(struct szemelylista)))) {
break;
}
if(horgony) {
elozo ->kov = llist;
} else {
horgony = llist;
}
elozo = llist;
llist -> kov = NULL;
llist->szemelyId = ct;
strcpy(llist->nev, s);
printf("Friends: "); //this is the problematic part I guess
getl(s, 50);
barat = atoi(s);
llist->baratok = barat;
while(barat != -1) {
getl(s, 50);
barat = atoi(s);
llist->baratok = barat; //until here
}
ct++;
}
llist = horgony;
printf("ID\Name\Friends\tFriends with text\n");
printf("--------------------------------------------\n");
while(llist) {
printf("\t%d\t%s\t%d\t\n", llist->szemelyId, llist->nev, llist->baratok);
llist = llist->kov;
}
}
您不能只為一個指針分配多次,而是以某種方式認為已存儲了多個值。 它不是那樣工作的。 每個賦值完全覆蓋該變量中的先前值。
您需要通過將其設置為固定大小的數組來實際管理該數組:
int baratok[100]; /* Max 100 numbers, no idea if this is sensible for you. */
或者通過在堆上分配動態數組(使用malloc()
),並在需要更多空間時使用realloc()
對其進行realloc()
)。
無論哪種情況,您都必須添加另一個變量,該變量跟蹤添加了多少個數字,直到當前分配的最大值。
內存管理比您預期的要復雜一些,您需要閱讀更多基本的C參考資料。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.