【发布时间】:2020-03-17 22:25:09
【问题描述】:
我有这个包含 100 部电影的数组(结构电影,我从以前加载的简单链表中获取数据),并且由于某种原因,当我尝试打印内容时(在这种情况下,只是电影的标题)它只显示 100 部电影中的 45 部电影。然后程序停止。 它是更大代码的一部分,但其余部分工作正常,所以我将发布我遇到问题的代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
// List of movies
struct Node{
Movie movie;
struct Node *next;
};
// Pointer to the first element of the list
typedef struct{
struct Nodo *head;
}List;
typedef struct{
int id;
char title[100];
char director[100];
char genre[100];
int likes;
int number_of_voters;
float rating;
int year;
int cost;
char color[100]; // "Color" or "BW"
}Movie;
typedef struct{
Movie movies[SIZE];
int cant; // Number of structs loaded
}Array;
void Initialize(List *l);
void FromListToArray(List l, Array *arr);
void PrintArray(Array arr, int length);
int main(){
List list; // Previously loaded with movies, which I copied from a txt file
Array a;
Initialize(&list);
FromListToArray(list, &a);
// Array previously loaded with 100 movies (index 0 to 99), so a.cant = 100
int length = a.cant - 1;
PrintArray(a, length)
return 0;
}
void PrintArray(Array arr, int length){
if (lenght < 0){ // Base
return;
}
// Inductive
printf("%s\n", arr.movies[length].title);
PrintArray(arr, sup-1);
}
/* Initializes a simply linked list */
void Initialize(List *l){
(l->head) = NULL;
}
/* Copies the data of "colored" movies (there are black and white movies too in the list) from a simply linked list into an array */
void FromListToArray(List l, Array *arr){
int i = 0;
arr->cant = 0;
struct Node *p;
p = l.head;
while ((p->next != NULL) && (arr->cant < SIZE)){
if (strcmp(p->movie.color, "Color\n")==0){
// Copy the content of the movie from the list into the array
arr->movies[i].id = p->movie.id;
strcpy(arr->movies[i].title, p->movie.title);
strcpy(arr->movies[i].director, p->movie.director);
strcpy(arr->movies[i].genre, p->movie.genre);
arr->movies[i].likes = p->movie.likes;
arr->movies[i].number_of_voters = p->movie.number_of_voters;
arr->movies[i].rating = p->movie.rating;
arr->movies[i].year = p->movie.year;
arr->movies[i].cost = p->movie.cost;
strcpy(arr->movies[i].color, p->movies.color);
arr->cant++;
i++;
}
p = p->next;
}
printf("Movies in the array ::: %d\n", arr->cant);
}
【问题讨论】:
-
很高兴您尝试为我们最小化代码。但它也需要完整。否则,通常会删除导致问题的实际代码(因为根据定义,您不知道问题出在哪里)。例如,在这种情况下,我们不知道
a.cant的值是多少。你说它是 100,但我们需要查看实际代码来验证这一点。请发帖minimal reproducible example -
也许这是一个stackoverflow... 考虑到每个
PrintArray的递归调用超过100*400char 的堆栈使用量,这将是相当合理的。您可能希望通过引用(指针)将Array传递给PrintArray函数,或者在其中动态分配movies。 -
类似于@grek40 所说的。对
PrintArray之类的东西使用递归不是一个好主意。每个递归调用都会占用堆栈的一部分,并且随着数组长度的增加可能会导致溢出(如果它尚未溢出当前的 100 大小)。一个简单的循环在这里会更好。当然,除非您需要将其作为作业/问题的一部分。 -
@kaylum 我需要为此使用递归。那么问题是它溢出数据并杀死进程?
-
好的,伙计们,我按照你说的做了,而且有效。所以它将是 void PrintArray(Array *arr, int length) 和 printf("%s\n", arr->movies[length].title);非常感谢。