Итак, я пытаюсь написать простую программу, которая принимает входные данные в виде целых чисел и добавляет их в блок памяти. Затем пользователь может ввести другой номер и продолжать делать это столько времени, сколько он хочет. Всякий раз, когда я запускаю программу, если я выбираю только 1 номер, она отображает неправильный номер при выводе списка, но если я пытаюсь ввести несколько чисел, происходит сбой программы. Любой вклад или совет будут оценены.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int *list;
char loop;
j = 1;
//alocates memory
list = calloc(j, sizeof(int));
if(list == NULL)
{
printf("Sorry the memory could not be alocated\n");
return 0;
} //end if
//this is where the user can enter the elements of the list
for(i = 0;i < j;i++)
{
//instructs the user to enter a value
printf("Enter elemint %d of the number list\n", j);
//stores value entered
scanf("%d", & *(list+i));
printf("Do you want to enter another number?\n Y yes\n N no\n");
//checks input
do
{
//gets input
scanf("%1s", &loop);
} //end do while
while(loop != 'Y' && loop != 'y' && loop != 'N' && loop != 'n');
if(loop == 'Y' || loop == 'y')
{
j++;
//reallocates memory
list = realloc(list, j*sizeof(int));
} //end if
else if(loop == 'N' || loop == 'n')
{
printf("Okay list complete\n");
} //end else if
else
{
printf("ERROR");
return 0;
} //end else
} //end for
printf("You entered\n");
//prints the elemints of the list
for(i = 0 ; i < j ; i++)
{
printf("%d ", *(list+i));
} //end for
free(list);
return 0;
}
РЕДАКТИРОВАТЬ Я выяснил проблему, но мое решение немного странно. Поэтому все, что я сделал, это инициализировал свою индексную переменную i внутри циклов for, а не в начале main. Также да, есть еще комментарии, и я исправил проблемы с форматированием, но они не имеют значения с точки зрения кода
/*
Description
This program takes input from the user by useing a resizeable list and then displays the list
Author
Paul Geoghegan
Date
25/01/20
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int j;
int *list;
char loop;
j = 1;
//alocates memory
list = calloc(j, sizeof(int));
//checks if memory has been allocated correctly
if(list == NULL)
{
printf("Sorry the memory could not be alocated\n");
return 0;
} //end if
//this is where the user can enter the elements of the list
for(int i = 0;i < j;i++)
{
//instructs the user to enter a value
printf("Enter elemint %d of the number list\n", j);
//stores value entered
scanf("%d", &*(list+i));
printf("Do you want to enter another number?\n Y yes\n N no\n");
//checks input
do
{
//gets input
scanf("%1s", &loop);
} //end do while
while(loop != 'Y' && loop != 'y' && loop != 'N' && loop != 'n');
if(loop == 'Y' || loop == 'y')
{
//increases j for use in reallocateing the memory block
j++;
//reallocates memory
list = realloc(list, j*sizeof(int));
} //end if
else if(loop == 'N' || loop == 'n')
{
printf("Okay list complete\n");
} //end else if
else
{
printf("ERROR");
return 0;
} //end else
} //end for
printf("You entered\n");
//prints the elemints of the list
for(int i = 0 ; i < j ; i++)
{
printf("%d ", *(list+i));
} //end for
//frees up memory and ends program
free(list);
return 0;
} //end program