我工作的语言是C。
我正在尝试使用内置c字符串函数的混合来获取标记列表(空格分隔)并将其“转换”为由引用拆分的标记列表。
像
这样的字符串echo“Hello 1 2 3 4”test test2
转换为
[echo] [“你好] [1] [2] [3] [4”] [测试] [test2]
然后我使用我的代码(在底部) 尝试 将其转换为类似
的内容[echo] [Hello 1 2 3 4] [test] [test2]
由于某种原因,引用语句中的第二个“标记”被覆盖。 这是在代码列表上运行的代码片段,并将其转换为新代码。
88 for (int i = 0; i < counter; i++) {
89 if ( (strstr(tokenized[i],"\"") != NULL) && (inQuotes == 0)) {
90 inQuotes = 1;
91 tokenizedQuoted[quoteCounter] = tokenized[i];
92 strcat(tokenizedQuoted[quoteCounter]," ");
93 } else if ( (strstr(tokenized[i],"\"") != NULL) && (inQuotes == 1)) {
94 inQuotes = 0;
95 strcat(tokenizedQuoted[quoteCounter],tokenized[i]);
96 quoteCounter++;
97 } else {
98 if (inQuotes == 0) {
99 tokenizedQuoted[quoteCounter] = tokenized[i];
100 quoteCounter++;
101 } else if (inQuotes == 1) {
102 strcat(tokenizedQuoted[quoteCounter], tokenized[i]);
103 strcat(tokenizedQuoted[quoteCounter], " ");
104 }
105 }
106
107 }
答案 0 :(得分:1)
简而言之,向char *
添加空格意味着它指向的内存需要更多字节。由于您没有提供它,因此您使用\0
覆盖以下“单词”的第一个字节,因此char *
将其解释为空字符串。请注意,写入未保留的位置是未定义的行为,因此可能会发生 ANYTHING (从分段错误到“正确”结果,没有错误)。
使用malloc
为扩展结果创建一个新的缓冲区,并为其提供足够的字节(如果free
'd,请不要忘记malloc
旧缓冲区。