新手编程(学校),我对这是怎样/为什么会发生这种情况感到困惑。
我有一个遍历元素数组的循环,对于每个元素我采用数组的整数,使用函数getelementsymbol将其转换为char,并使用strcat追加到我的临时数组。我遇到的问题是我的临时数组的元素包含继续它的元素的残余。这是我的代码片段。我收到的输出是:
WORD1
word1word2
word1word2word3
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);
}
答案 0 :(得分:1)
首先,您的s1
未初始化。 strcat
函数将新字符串附加到现有字符串。这意味着您的s1
必须从一开始就是字符串。未初始化的char数组不是字符串。一个好主意是将您的s1
声明为
char s1[MAX_GENERATED_WORD_LENGTH] = { 0 };
或至少做
s1[0] = '\0';
开始你的周期之前。
其次,您的getElementSymbol
函数返回char *
指针。那个指针指向哪里?谁管理它指向的记忆?这在您的代码中并不明显。该函数可能返回一个无效指针(如指向本地缓冲区的指针),这就是为什么可能会看到各种异常。没有看到如何实施它就没有办法说。
答案 1 :(得分:0)
strcat
应该附加到字符串。如果要覆盖现有字符串,请使用strcpy
。如果你真的想要,你也可以在s1[0] = '\0';
之前使用strcat
“空白”字符串,但看起来你真的想要strcpy
。
从上面的代码段开始,您甚至不清楚为什么需要s1
- 您只需打印s2
...