【问题标题】:Copy value of char array to 2D array将 char 数组的值复制到二维数组
【发布时间】:2017-08-15 07:05:21
【问题描述】:

正如您在下面看到的,我创建了一个二维字符串数组。我也使用一个名为“缓冲区”的字符数组。我想将缓冲区的值复制到二维数组的 [5][0] 位置。 问题是当缓冲区的值发生变化时,数组单元格的值也会发生变化。 我想保留第一个值。

#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]);
    }
}

输出:

 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

【问题讨论】:

  • 你的问题是什么?
  • 那么你的问题到底是什么?请具体说明。
  • 我希望第一个值是永久的

标签: c arrays char 2d


【解决方案1】:

问题在于 strNameList[pos][0] 指向buffer 并且它不是一个独立的存储位置,因为它只是一个指针,您可以使用 bufferstrNameList[pos][0] 修改它,因为两者指向内存中的同一个地方。

不要在同一个字符串数组中混合指向字符串字面量的指针和指向非常量数组的指针,而是使用

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

你也会看到区别

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

你需要一个

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

稍后,当您不再需要指针时。

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多