c - strcat (s1, s2) 对我的临时变量数组仍然很明显

标签 c arrays

编程(学校)新手,我对发生这种情况/为什么发生有点困惑。

我有一个循环遍历元素数组,对于每个元素,我获取数组的整数,使用函数 getelementsymbol 将其转换为 char,并使用 strcat 附加到我的临时数组。我遇到的问题是我的临时数组的元素包含处理它的元素的剩余部分。这是我的代码片段。我收到的输出是这样的:

单词1

字1字2

字1字2字3

char* elementsBuildWord(const int symbols[], int nbSymbols){
/*  ROLE            takes a list of elements' atomic numbers and allocate a new string made
                    of the symbols of each of these elements
PARAMETERS      symbols     an array of nbSymbols int which each represent the atomic number
                                of an element
                    nbSymbols   symbols array's size
RETURN VALUE    NULL    if the array is of size <= 0
                            or if one of the symbols is not found by our getElementSymbol function
                    other   the address of a newly allocated string representing the    concatenation
                            of the names of all symbols
 */
    char s1[MAX_GENERATED_WORD_LENGTH];
    int y;
    char *s2;
    size_t i;

    for (i = 0; i < nbSymbols; i++){
        y = symbols[i];
        s2 = getElementSymbol(y);
        strcat(s1, s2);         
    }
    printf("%s ", s1);
}

最佳答案

首先,您的s1尚未初始化。 strcat 函数将新字符串附加到现有字符串。这意味着您的 s1 从一开始就必须是一个字符串。未初始化的 char 数组不是字符串。一个好主意是将您的 s1 声明为

char s1[MAX_GENERATED_WORD_LENGTH] = { 0 };

或者至少这样做

s1[0] = '\0';

开始周期之前。

其次,您的 getElementSymbol 函数返回一个 char * 指针。该指针指向哪里?谁管理它指向的内存?这从您的代码中并不明显。该函数可能返回无效指针(例如指向本地缓冲区的指针),这就是为什么可能会看到各种异常情况。如果不看看它是如何实现的,就没有办法说。

关于c - strcat (s1, s2) 对我的临时变量数组仍然很明显,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849456/

相关文章:

c - 小写<-->大写函数未按计划运行

c - 在频繁打开的 block 作用域 { } 中声明自动变量时是否会损失效率?

cudaEventRecord() 在 Visual Studio CPU 代码上计时不正确

c - 在 void 函数中通过引用而不是值传递结构

javascript - ReactJS:用新值替换数组中的对象替换整个数组

javascript - 如何获取随机播放函数的输出并在 DOM 元素周围移动?

javascript - 递归地反转数组中的元素

c - C 中 AES crypt 的检查字符串在哪里?

javascript - 在 React 中的 .map 迭代中的单个元素上使用 onMouseEnter

javascript - AngularJS 过滤不是对象数组的 JSON 对象 {}