我正在编写一个C程序来遍历Linux中的一个文件系统,记录每个文件的内存,并在最后显示一个直方图。在将指针传递给structs时,我遇到了一些问题,而且我不太熟悉如何在C中传递这些结构。
我试图将头指针传递到readDirectory函数中,但它的行为方式是,每次调用该函数时,它都会传入一个空的链表头部。在函数中,它像预期的那样添加节点,但每次递归调用它自己时,似乎列表都被清除了,头部又回到了well。我假设我传递了错误的节点,所以有人能告诉我传递它们的正确方法吗,或者告诉我一个很好的解释它的好资源?
当我将它传递给printHistrogram函数时,问题也会发生,但如果我可以在其他地方修复它,我也会知道如何在这里修复它。
提前谢谢。-Chris
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
struct memList
{
int mem;
struct memList* next;
};
void readDirectory(const char*, struct memList*);
void printHistogram(struct memList*, int binSize);
int main(int argc, char* argv[])
{
struct memList* head = NULL;
if (argc != 3)
{
perror("Not enough parameters\n");
}
int binSize = strtol(argv[2], NULL, 10);
readDirectory(argv[1], head);
printHistogram(head, binSize);
return 0;
}
void readDirectory(const char * passedDir, struct memList* head)
{
DIR * directory = opendir(passedDir);
if (directory == NULL)
printf("Unable to open directory\n");
while(1)
{
struct dirent * current;
current = readdir(directory);
if (!current)
break;
if ((current->d_type == 4) && (strcmp(current->d_name, ".") != 0) && (strcmp(current->d_name, "..") != 0)) //current path is directory but not the current or parent
{
char * path = malloc(sizeof(char) * 300);
strcpy(path, passedDir);
if (path[strlen(path) - 1] != '/')
strcat(path, "/");
strcat(path, current->d_name);
readDirectory(path, head);
free(path);
}
else
{
char * path = malloc(sizeof(char) * 300);
strcpy(path, passedDir);
if (path[strlen(path) - 1] != '/')
strcat(path, "/");
strcat(path, current->d_name);
struct stat tempStat;
stat(path, &tempStat);
free(path);
int temp = tempStat.st_size;
if (head == NULL)
{
head = (struct memList*)malloc(sizeof(struct memList));
head->next = NULL;
head->mem = temp;
}
else
{
struct memList * tempStruct = (struct memList*)malloc(sizeof(struct memList));
tempStruct->next = head;
tempStruct->mem = temp;
head = tempStruct;
//printf("mem is %d\n", head->mem); //debugging
}
}
}
closedir(directory);
}
void printHistogram(struct memList* head, int binSize)
{
int numElements = 10;
int * array = (int*)malloc(sizeof(int) * numElements);
for (int i = 0; i < numElements; i++)
array[i] = 0;
while(head != NULL)
{
//printf("mem is %d\n", head->mem); //debugging
int temp = head->mem;
int temp2 = ((temp - (temp % binSize)) / binSize);
if ((temp2 + 1) > numElements)
{
int * new = realloc(array, (sizeof(int) * (temp2 + 1)));
array = new;
for (int i = numElements; i < (temp2 + 1); i++)
array[i] = 0;
numElements = (temp2 + 1);
}
array[temp2] += 1;
head = head->next;
}
for (int i = 0; i < numElements; i++)
{
printf("%d\n", array[i]);
printf("Block %d: ", i + 1);
for (int j = 0; j < array[i]; j++)
printf("*");
printf("\n");
}
}
发布于 2019-03-18 08:39:15
学习“通过引用传递”和“通过值传递”。C是通过值传递的。
如果你想修改head
,使它的值保持在readDirectory
之外,那么你需要将一个指针传递给一个指针。
https://stackoverflow.com/questions/55213364
复制相似问题