#c
#c
Вопрос:
Правильно ли я освобождаю память в этой программе, используя только free(lineArr) в конце main()?
Я все еще не могу понять, что вызывает проблему со всеми символами в моем выводе (изображение прилагается). Я знаю, что это, вероятно, что-то базовое в том, как у меня настроены циклы for .. все печатается правильно при первом запуске после компиляции, но не при втором запуске. С чего бы это вдруг?
Спасибо
// When the sum of proper divisors for a number is the same as the number
// itself, the "status" of that sum may be considered "perfect"; when less,
// "deficient", and when greater than, "abundant".
//
// This program takes two extra command-line arguments after the executable
// name: an integer and a character. The integer will be the number of
// numbers past 2 to print statuses and histogram bars for; the character
// will be used to construct a histogram bar with height = to the sum of
// divisors for a particular number. Example arguments: ./a.out 6 '*'
// Example output:
// 2 is Deficient *
// 3 is Deficient *
// 4 is Deficient ***
// 5 is Deficient *
// 6 is Perfect ******
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int sumOfDivisiors(int aNum); //prototype for sumOfDivisiors function
typedef struct{ //define a structure called "line" with three members
int lineNum;
int sum;
char status[10];
}line;
int main(int argc, char *argv[]){ //main will accept command line arguments
int howMany;
char usrChar;
line whichLine;
if(argc < 3){
printf("Error: must enter 3 command line arguments.n");
exit(1);
}
sscanf(argv[1],"%d", amp;howMany);
sscanf(argv[2], "%c", amp;usrChar);
line** lineArr = malloc(howMany * sizeof(line*)); //allocate mem for array of struct ptrs
if (lineArr == NULL){
printf("Error: trouble allocating memory. Exiting.n");
exit(1);
}
for (int n = 2; n <= howMany; n ){ //loop to call func initialize lineNum, sum, status for current line
int sumResult = sumOfDivisiors(n);
lineArr[n] = malloc(sizeof(line)); //allocate mem for pointer to current line struct
if (lineArr[n] == NULL){
printf("Error: trouble allocating memory. Exiting.n");
exit(1);
}
line* temp = lineArr[n];
temp->lineNum = n;
temp->sum = sumResu<
if (temp->sum == n){
strcpy(temp->status, "Perfect");
} else if (temp->sum < n){
strcpy(temp->status, "Deficient");
} else {
strcpy(temp->status, "Abundant");
}
}
for (int i = 2; i <= howMany; i ){ //loop to print formatted results
printf("= %-10s ", i, lineArr[i]->status);
for (int j = 0; j < lineArr[i]->sum; j ){
printf("%c", usrChar);
}
printf("n");
}
free(lineArr); //free dynamically allocated memory
return 0;
}
//Definition for sumOfDivisiors function. This function accepts an int number
//as an argument. It takes that number, finds all proper divisors (divisors
//less than the number itself), then returns the integer result of adding
//up all these divisors.
int sumOfDivisiors(int aNum){
int result = 0;
int i;
for (i = 2; i <= sqrt(aNum); i ){
if (aNum % i == 0){
if (i == (aNum/i)){
result = i;
} else {
result = (i aNum/i);
}
}
}
return(result 1);
}
Комментарии:
1. Почему вы используете массив указателей struct вместо простого массива struct ?
2. Ответ на первый вопрос: нет, вы неправильно освобождаете память. Сначала вы выделяете место для набора указателей и только затем выделяете место для своих структур. В итоге вы освобождаете только первое выделение. Подумайте о том, чтобы просто распределить данные прямо вверх, т.Е.
line *lineArr = malloc(howMany * sizeof(line));
3. Ответ на второй вопрос:
result = (i aNum/i);
4. Второй цикл работает правильно, ваша
sumOfDivisors()
функция неверна.5. Зачем вам вообще нужны struct и array ? Вы можете просто распечатать выходные данные в первом цикле.