gpt4 book ai didi

C - 复制字符串数组

转载 作者:行者123 更新时间:2023-11-30 16:29:23 26 4
gpt4 key购买 nike

我的指针有问题。我正在尝试将数组“names”的内容复制到数组“self.names”。在循环中,当我打印指针的值时,指针指向第一个元素,但是当我将其作为 strcpy 的参数时,指针指向第三个元素。我做错了什么?

参数.h:

#ifndef ARGUMENT_H
#define ARGUMENT_H

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Argument{
char **names;
};
struct Argument Argument_new(char**);

#endif

参数.c:

#include "argument.h"

struct Argument Argument_new(char **names){
struct Argument self;
size_t namesc=0;
char **names_start=names;
while(*names++){
namesc++;
}
self.names=malloc(namesc*8);
for(names=names_start;*names;names++){
printf("%s\n",*names);
*self.names=malloc(sizeof(*names));
strcpy(*self.names,*names);
}
names=names_start;
printf("%s\n%s\n",self.names[0],names[0]);
printf("%s\n%s\n",self.names[1],names[1]);
}

main.c:

#include "argparse/argparse.h"

int main(int argc, const char **argv){
char *a[]={"abc","def","ghi",NULL};
Argument_new(a);
return 0;
}

最佳答案

在循环的每次迭代中,您都会将当前字符串复制到 *self.names,即 self.names[0],即列表。因此,当您打印 self.names[0] 时,只会显示您复制的最后一个内容,即 names 列表中的最后一个字符串。

您需要跟踪您所在的名称并将其复制到相关的数组成员中。

此外,sizeof(*names) 给出 char * 的大小,而不是它包含的字符串的长度。您需要 strlen 来实现这一点,并确保在末尾为空字节添加 1。同样,在分配列表时,不要使用魔数(Magic Number) 8,而是使用 sizeof(*names) 来代替:

int i;
self.names=malloc(namesc*sizeof(*names));
for(i=0,names=names_start;*names;names++,i++){
printf("%s\n",*names);
self.names[i]=malloc(strlen(*names) + 1);
strcpy(self.names[i],*names);
}

关于C - 复制字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com