Your definition for the array is incorrect, it should be:
int t[n];
Note that you do not need to declare a local array for your purpose, but you should check for proper conversion by scanf
.
Note also that insert_end
probably does not take a list ***
argument.
Here is an improved version:
void tab2list(int n, list **T) {
int i, res, value;
for (i = 0; i < n;) {
printf("Entrez l'element %d du tableau\n", i + 1);
res = scanf("%d", &value);
if (res == 1) {
insert_end(value, T);
i++;
} else
if (res == -1) {
printf("fin de fichier inattendue\n");
break;
} else {
scanf("%*s"); /* skip the offending input */
}
}
}
If you need to perform some extra checks on the values before inserting them into the list, you can split the code in 2 loops:
void tab2list(int n, list **T) {
int i, res, t[n];
for (i = 0; i < n;) {
printf("Entrez l'element %d du tableau\n", i + 1);
res = scanf("%d", &t[i]);
if (res == 1) {
i++;
} else
if (res == -1) {
printf("fin de fichier inattendue\n");
return;
} else {
scanf("%*s"); /* skip the offending input and try again */
}
}
/* perform some extra checks on the array... */
for (i = 0; i < n; i++) {
insert_end(t[i], &T);
}
}
EDIT after you gave further information on your actual problem, here is a fixed version:
#define z 50
struct list {
int val;
struct list *next;
};
typedef struct list list;
void tab2list(int *t, int n, list **T) {
int i;
for (i = 0; i < n; i++) {
insert_end(t[i], T);
}
}
int main(void) {
int n, i;
int t[z];
list *tete = NULL;
printf("Entrez le nb d'element de ton tableau(max 50)\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Entrez l'element %d du tableau\n", i + 1);
scanf("%d", &t[i]);
}
tab2list(t, n, &tete);
afficher_list(tete);
return 0;
}
19
solved I can’t run this code of coverting an array into a list