【问题标题】:First element in two dimensional array being overwritten - C二维数组中的第一个元素被覆盖 - C
【发布时间】:2013-03-03 11:18:18
【问题描述】:

我遇到同样的问题已经有一段时间了,无论进行多少研究,我似乎都无法解决这个问题。我已经提出了一些理论,为什么它可能会发生。

基本上,我正在编写一个简单的 C shell,但在尝试实现要存储在二维数组中的别名时遇到了一个烦人的错误。每当我尝试为数组分配多个别名时,它都会覆盖第一个元素。

我认为这可能归结为:

  1. 再次标记输入时出现内存问题
  2. 数组“衰减”和指针问题
  3. 我的编译器讨厌我。

这是我的代码:

void fillArray(char* tokens[], char* aliasArray[ALIAS_NO][TOKEN_NUM]) {
    /* Integer for the for loop */
    int i;
    /* Counter for attribute addition */
    int counter = 2;
    /* Onto the search */
    for (i = 0; i < ALIAS_NO; i++) {
        if (aliasArray[i][0] == NULL) { /* If there is a space here */
            aliasArray[i][0] = tokens[counter-1]; /* Assign the alias */
            while (tokens[counter] != NULL) { /* While there is still stuff left */
                aliasArray[i][counter-1] = tokens[counter]; /* Add it in */
                counter++; /* Increment the counter */
            }
            return;
        }
    }
    return;
}

其中 ALIAS_NO 和 TOKEN_NUM 分别是值 10 和 50 的预处理器指令。

当我打印 i 的状态时检查条目是否为空,并且我还将多维数组中的每个元素初始化为 NULL。

任何帮助将不胜感激。我已经用头撞墙太久了。

谢谢:)

编辑:我也尝试过使用 strcpy() 函数。不幸的是,这会引发分段错误。

编辑:新代码

 void fillArray(char* tokens[], char* aliasArray[ALIAS_NO][TOKEN_NUM]) {
/* Integer for the for loop */
int i;
/* Counter for attribute addition */
int counter = 2;
/* Buffer */
char buffer[200];
/* Onto the search */
for(i = 0; i < ALIAS_NO; i++) {
    if(aliasArray[i][0] == NULL) { /* If there is a space here */
        strcpy(buffer, tokens[counter-1]);
        aliasArray[i][0] = buffer; /* Assign the alias */
        while (tokens[counter] != NULL) { /* While there is still stuff left */
            strcpy(buffer, tokens[counter]);
            aliasArray[i][counter-1] = buffer; /* Add it in */
            counter++; /* Increment the counter */
        }
        return;
    }
}
return;
}

【问题讨论】:

  • 在执行 strcpy 之前,您是否分配了要复制的新字符串?
  • 这不会影响我的返回值和/或分配吗?还是您的意思是我可以将tokens[counter] 的值复制到缓冲区中,然后将aliasArray[i][counter] 分配给该缓冲区?
  • 这就是我的意思。您可能每次都对令牌使用相同的缓冲区并用不同的值填充它们。由于您将指向这些缓冲区的指针存储在 aliasArray 中,因此 aliasArray 将始终反映放入这些缓冲区中的最新值。
  • 那我试试看! :) 现在我想起来了,这更有意义,对我所做的事情也更明智。谢谢,我会告诉你情况如何。
  • 恐怕它还在做同样的事情。 aliasArray 中的第一个元素 [0][0] 将被替换为添加到第一个条目之后的任何内容。

标签: c arrays pointers memory multidimensional-array


【解决方案1】:
for(i = 0; i < ALIAS_NO; i++)
{
    if(aliasArray[i][0] == NULL)
    {
        aliasArray[i][0] = strdup(tokens[counter-1]);
        while (tokens[counter] != NULL)
        {
            aliasArray[i][counter-1] = strdup(tokens[counter]);
            counter++;
        }
        break;
    }
}

【讨论】:

  • 这是你想要的基础。您现在对这些字符串的生命周期负责,因此您需要确保在使用完它们后free它们。
  • 完美运行,非常感谢你们的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 2021-03-20
  • 1970-01-01
相关资源
最近更新 更多