新的C
在这里,我已经找到了以下算法来连接字符串,同时搜索书籍在线:
Algorithm: STRING_CONCAT (T, S)
[string S appends at the end of string T]
1. Set I = 0, J = 0
2. Repeat step 3 while T[I] ≠ Null do
3. I = I + 1
[End of loop]
4. Repeat step 5 to 7 while S[J] ≠ Null do
5. T[I] = S[J]
6. I = I + 1
7. J = J + 1
[End of loop]
8. Set T[I] = NULL
9. return
基本上,我已经尝试用我目前与C
的工作知识来实现这一点。然而,我不确定如何让char*
指针正确指向函数内部。例如,
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
const char* stringConcat(char* T, char* S){
int i = 0;
int j = 0;
char* Q;
while(*S[i] != NULL & *T[i] != NULL){
i += 1;
while(*S[j] != NULL){
*T[i] = *S[j];
i += 1;
j += 1;
}
}
*T[i] = NULL;
return *T
}
int main(void){
char* sentence = "some sentence";
char* anotherSentence = "another sentence";
const result;
result = stringConcat(sentence, anotherSentence);
return EXIT_SUCCESS;
}
我得到一个日志错误输出如下:
exe_4.c:8:11: error: indirection requires pointer operand ('int' invalid)
while(*S[i] != NULL & *T[i] != NULL){
^~~~~
exe_4.c:8:27: error: indirection requires pointer operand ('int' invalid)
while(*S[i] != NULL & *T[i] != NULL){
...
...
要连接两个字符串,代码需要一个有效的位置来保存结果。
试图在未定义行为(UB)中写入字符串字面值。
// v------v This is a string literal and not valid place to save.
stringConcat(sentence, anotherSentence);
请使用可写字符数组。
// Make it big enough
char sentence[100] = "some sentence";
char* anotherSentence = "another sentence";
stringConcat(sentence, anotherSentence);
连接代码试图用*S[i]
解除对char
的引用。这是不可能的。
相反,将目标字符串遍历到其末尾,然后附加源字符串的每个字符。
const char *stringConcat_alt(char *destination, const char* source) {
const char *t = destination;
// Get to the end of destination
while (*destination) {
destination++;
}
while (*source) {
*destination++ = *source++;
}
*destination = 0;
return t;
}
不要对空字符使用NULL
。使用' '
。NULL
是一个空指针,可能不会转换为char
0。