【发布时间】:2018-02-22 01:23:14
【问题描述】:
我正在尝试解决 CS50 的一些问题集。我需要提取字符串“stra”的前两个字符,然后将它们连接起来并转换为字符串,然后将该字符串与数组中的字符串进行比较。我已经大量阅读,在 C 中没有字符串,只有字符数组,但在 CS50 中它们使用字符串声明类型。当我运行代码时,它给了我以下错误
运行时错误:类型“字符串 [4]”的索引 4 超出范围
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void){
string stra = "GH7";
int x = 0;
//extract first two chars of stra
char strb[3] = {stra[0], stra[1], '\0'};
//concatenate chars
string strc = strb;
string letters[] = {"AB","CD","ED","GH"};
for (int i = 0, n = sizeof(letters); i < n; i++)
{
if (strc == letters[i]) // <--the error happens here
{
break;
}
else
{
x++;
}
}
printf("%i", x);
}
它给了我这个错误
运行时错误:类型“字符串 [4]”的索引 4 超出范围
【问题讨论】: