【发布时间】:2017-06-19 21:18:43
【问题描述】:
我需要计算“字符串列表”中有多少个字符串。每个字符串像往常一样以 NUL 字符 ('\0') 结尾,列表以连续两个 NUL 字符结尾。
我写了一个函数,但我不断收到分段错误:
int numStrsInList(const char* strList) {
int count = 0;
int flag = 0;
if(!(*strList))
return -1;
while (flag != 2) {
if (!(*strList)) {
count++;
flag++;
}
else
flag = 0;
strList++;
}
return count;
}
例如:
const char* empty = "\0";
const char* one = "Hell0 \t\n\v\f\rw0r1d\0";
const char* two = "Hello\0 \t\0";
const char* simple = "Hello\0world\0!\0";
例如调用:
numStrsInList(empty)
numStrsInList(one)
numStrsInList(two)
numStrsInList(simple)
对于这个字符串,输出应该是:
0
1
2
3
【问题讨论】:
-
你的函数本身意义有限。我们通常希望您提供minimal reproducible example。另外,不要显示带有行号的代码。
-
第 1 到 34 行在哪里?另外:如果函数有效,
count将是 1 太多或 2 太多,因为不清楚列表如何结束。请发布显示问题的Minimal, Complete, and Verifiable example。将输入、预期输出和实际输出显示为问题中的文本。 -
你怎么知道哪个
'\0'是列表中的最后一个'\0'?如果你不能明确地知道 "list" 的结尾是什么,那么你只会在列表结尾之后扯掉 Undefined Behavior" 分段错误. -
@David C. Rankin,关于“你怎么知道哪个 '\0' 是列表中的最后一个 '\0'?”,如果上一个角色也是
\0。 -
@ikegami 请喝杯咖啡。
标签: c string algorithm segmentation-fault