C 当我打印动态分配的数组时,它只打印最后一个值
我尝试制作一个程序,它将获取一个目录,并将其所在目录中的文件路径保存在一个动态分配的数组中。我插入了路径,但当我试图打印数组时,输出只是最后一条路径。我是动态分配阵列中的新手,所以任何建议都会帮助我 下面是代码和输出C 当我打印动态分配的数组时,它只打印最后一个值,c,C,我尝试制作一个程序,它将获取一个目录,并将其所在目录中的文件路径保存在一个动态分配的数组中。我插入了路径,但当我试图打印数组时,输出只是最后一条路径。我是动态分配阵列中的新手,所以任何建议都会帮助我 下面是代码和输出 #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <dirent.h> #include <s
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <stdbool.h>
int main(int argc,char* argv[]){
char** arrayWithPaths;
int counter=0;
int pathCounter=0;
char *path= (char*) malloc(100*sizeof(char*));
//If the argv is equal with 1 then there is not a path
//If the argv is equal with 2 then there is a path
//If the argv is not equal with 1 neither with 2 then there is more than 1 path
if (argc == 1 )
{
}else if (argc == 2){
arrayWithPaths = calloc(50,sizeof(char*));
DIR *dir = opendir(argv[1]);
if (dir != NULL){
struct dirent *dirP;
while ((dirP = readdir(dir)) != NULL)
{
counter++;
if (counter > 2)
{
int len = strlen(argv[1]);
char *lastLetter = argv[1]+len-1;
if (*lastLetter != '/')
{
sprintf(path,"%s/%s", argv[1], dirP->d_name);
arrayWithPaths[pathCounter]=path;
}else{
sprintf(path,"%s%s", argv[1], dirP->d_name);
arrayWithPaths[pathCounter]=path;
}
pathCounter++;
}
}
for (int i = 0; i < pathCounter; i++)
{
printf("%d", i);
printf("%s\n",arrayWithPaths[i]);
}
free(arrayWithPaths);
closedir(dir);
free(path);
}else if (ENOENT == errno){
printf("Directory does not exist\n");
}
}else{
printf("Input only one path!");
return 1;
}
return 0;
}
我想要的输出
/mnt/c/Users/user/Desktop/lslab/text/2.txt
/mnt/c/Users/user/Desktop/lslab/text/3.txt
/mnt/c/Users/user/Desktop/lslab/text/4.txt
/mnt/c/Users/user/Desktop/lslab/text/5.txt
/mnt/c/Users/user/Desktop/lslab/text/emptyOne.txt
/mnt/c/Users/user/Desktop/lslab/text/nameOfSomething.txt
好的,path
是指向您分配的单个内存块的指针
arrayWithPaths[pathCounter]=path;
每次通过循环时,将path
的值添加到数组中。但是path
的值永远不会改变,它总是指向在进入循环之前分配的相同内存块
因此,在最后,您将遍历循环并打印数组中的每个条目。但是数组中的每个条目都是指向开始时分配的内存块的同一个指针,该内存块现在恰好包含最后放入的内容
您需要在循环中的每次迭代中分配一个新的内存块,并且每次都需要向数组添加不同的值
一种简单的方法可以做到这一点:
arrayWithPaths[pathCounter]=strdup(path);
strdup
函数每次分配一个新的内存块,并将path
指向的字符串复制到其中
好的,path
是指向您分配的单个内存块的指针
arrayWithPaths[pathCounter]=path;
每次通过循环时,将path
的值添加到数组中。但是path
的值永远不会改变,它总是指向在进入循环之前分配的相同内存块
因此,在最后,您将遍历循环并打印数组中的每个条目。但是数组中的每个条目都是指向开始时分配的内存块的同一个指针,该内存块现在恰好包含最后放入的内容
您需要在循环中的每次迭代中分配一个新的内存块,并且每次都需要向数组添加不同的值
一种简单的方法可以做到这一点:
arrayWithPaths[pathCounter]=strdup(path);
strdup
函数每次分配一个新的内存块,并将path
指向的字符串复制到其中。strdup()
是POSIX,而不是标准C,因此在非POSIX系统上可能不可用。然而,复制几乎是微不足道的,这可能是它不是标准C的原因之一。strdup()
是POSIX,而不是标准C,因此它可能在非POSIX系统上不可用。然而,复制几乎是微不足道的,这可能是它不是标准C的原因之一。