gpt4 book ai didi

c - 在 C 中复制字符串数组时出错

转载 作者:行者123 更新时间:2023-11-30 20:22:37 25 4
gpt4 key购买 nike

我有两个包含字符串的指针数组。第一个从文件中逐行读取并填充。我想将字符串从第一个复制到第二个,但在某些时候进行一些更改。奇怪的是,当我使用代码使用早期函数中的相同方法从文件中删除一个人(某些行)时,它工作过……

下面是代码:

void verificare() {
int nrInt = 0, linieInt = 0;
system("cls");
FILE *fisier, *fisier2;
char buffer[1000];
char* v[100], w[100], c[100], nume[100];
char numeFisier[100], rasp[100];
int i = 0, j = 0, k = 0, k1 = 0, k2 = 0, l = 0, cont = 1, pozVal;

printf("Enter the name of the file: ");
scanf("%s", numeFisier);

fisier = fopen(numeFisier, "rt");


while(!feof(fisier))
{
while(fgets(nume, sizeof nume, fisier))
{
v[i] = (char*) malloc(100);
v[i] = strdup(nume);
i++;
}
}

//Checking and reviewing the array with some formatting in the console:
for (j = 0; j < i; j+=4)
{
printf("\n");
printf("Record Nr.: %d \n", cont);
printf("Name: %s", v[j] );
printf("Surname: %s", v[j + 1] );
printf("Age: %s", v[j + 2] );
printf("\n");
cont++;
}

//Copying the from array1( v[] ) to array2( c[] )

for (k = 0; k < i; k++)
{
c[k] = (char*) malloc(1000);
strncpy(c[k],v[k],100);
} // this for loop works in another earlier function ......


}

我也尝试过使用这些方法:

    strcpy(c[k], v[k]);
memcpy(c[k], v[k], 1000);
snprintf(c[k], 1000, "%s", v[k]);

// Or
calloc() istead of malloc()

我真的不明白我哪里错了......

最佳答案

尝试更改您的声明:

char *v[100], *w[100], *c[100], *nume[100];

编辑:要点是,当您在同一行上声明多个指针时,每个变量都需要一个星号。例如

char *a, *b;

声明两个字符指针,而

char *a, b;

将 a 声明为 char 指针,但将 b 声明为 char。

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

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