Philip D. Philip D. - 9 months ago 26
C Question

Error copying array of strings in C

I have two to arrays of pointers that contains strings. The first one reads from a file line by line and gets populated. I want to copy the strings from the first to the second but at some point with some changes.The odd thing is that when I used the code to remove a person (some lines) from the file with the same methods in an earlier function it worked.... .

Here is the code below:

void verificare() {
int nrInt = 0, linieInt = 0;
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(fgets(nume, sizeof nume, fisier))
v[i] = (char*) malloc(100);
v[i] = strdup(nume);

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

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

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


I also tryed to use these methods :

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

// Or
calloc() istead of malloc()

I really don't understand where i get it wrong....


Try changing your declaration:

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