Witam,
chce przekazać wskaźnik listy jednokierunkowej do funkcji, aby dodać element na pierwszym miejscu (musi być to w funkcji) i tutaj zaczęły się problemy, ponieważ w mainie działa, a w funkcji już nie jest tak miło.
Mam nadzieję, że znajdzie się ktoś kto mi wyjaśni o co chodzi, ponieważ jestem laikiem w C, więc błąd może być błahy.
Ogólnie doszedłem do momentu kiedy zamiast nadpisać 1 elementu listy nadpisują się wszystkie tą samą wartością.
// lista.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <windows.h>
#pragma warning(disable: 4996)
#pragma warning(disable: 4305)
typedef struct listElem{
int val;
struct listElem * next;
} Lista;
void list(listElem *lista){
while(lista){
printf("%d > ", lista->val);
lista = lista->next;
}
printf("\n");
}
void addElement(Lista *lista, int index, int val){
Lista *temp, *curr;
int i=0;
temp = (Lista*) malloc(sizeof Lista);
curr = (Lista*) malloc(sizeof Lista);
curr = lista;
while(curr){
if(i == index){
temp->val = val;
temp->next = *&lista;
*lista = *temp;
break;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Lista *head, *curr;
int i,n;
head = NULL;
printf("Podaj ile elementow ma miec lista:");
scanf("%d", &n);
for(i = 0; i < n; i++) {
curr = (Lista*) malloc(sizeof(Lista));
curr->val = i;
curr->next = head;
head = curr;
}
addElement(head, 0, 10);
for(int i =0;i<3; i++){
printf("%d", head->val);
head = head->next;
}
return 0;
}