Fotis455 Fotis455 -4 years ago 80
C Question

Copy value of char array to 2D array

As you can see below i create a 2D array of strings. Also i use a char array named "buffer". I want to copy the value of buffer to the [5][0] position of the 2D array.
The problem is that when the value of buffer changes, the value of the cell of the array also changes.
I want to keep the first value.

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

char * strNameList[10][2] = {
{"Luca", "Daniel"} ,
{"Vivan", "Desmond"},
{"Abdul", "Justin"},
{"Nina", "Marlene"},
{"Donny", "Kathlene"}
};

int main()
{
int j, i;
int pos = 5;
char buffer[10204];

strcpy(buffer, "A Value");

strNameList[pos][0] = buffer;
strNameList[pos][1] = "Surname";
for (i = 0; i < 9; i++) {
printf("\n");
for (j = 0; j < 2; j++)
printf(" %s", strNameList[i][j]);
}

strcpy(buffer, "B Value");
for (i = 0; i < 9; i++) {
printf("\n");
for (j = 0; j < 2; j++)
printf(" %s", strNameList[i][j]);
}
}


Output:


Luca Daniel
Vivan Desmond
Abdul Justin
Nina Marlene
Donny Kathlene
A Value Surname


Luca Daniel
Vivan Desmond
Abdul Justin
Nina Marlene
Donny Kathlene
B Value Surname

Answer Source

The problem is that strNameList[pos][0] points to buffer and it's not an independant storage location, since it's simply a pointer you can modify it using either buffer or strNameList[pos][0] because both point to the same place in memory.

Don't mix pointers to string literals, and pointers to non-const arrays in the same array of strings, instead use

strNameList[pos][0] = strdup(buffer);

and you will see the difference, likewise

strNameList[pos][1] = strdup("Surname");

you will need a

free(strNameList[pos][0]);
free(strNameList[pos][1]);

later, when you no longer need the pointers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download