0

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
3
  • What is your question? Commented Mar 22, 2017 at 22:40
  • So what actually is your problem then? Be specific about it. Commented Mar 22, 2017 at 22:41
  • I want the first value to be permanent Commented Mar 22, 2017 at 22:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.