[英]Passing pointer to struct in C?
我正在做一个C程序来遍历Linux中的一个文件系统,记录每个文件的内存,最后吐出一个直方图。 我在将指针传递给结构时遇到问题,并且不太熟悉如何在 C 中传递这些指针。
我试图将我的头指针传递到我的 readDirectory 函数中,但它的行为方式,每次调用该函数时都会传入一个空链表头。 在函数中,它按预期添加节点,但每次递归调用自己时,似乎列表已被清除,头部又恢复为 NULL。我假设我传递错误,所以有人可以告诉我传递它们的正确方法,或者给我指出一个很好的资源来解释它?
当我将它传递给 printHistrogram 函数时,这个问题也会发生,但如果我可以在其他地方修复它,我也会知道如何在这里修复它。
提前致谢。 -克里斯
#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");
}
}
研究“按引用传递”和“按值传递”。 C 是按值传递。
如果您希望修改head
以使其将其值保留在readDirectory
之外,那么您需要将指针传递给一个指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.