我正在尽我所能返回一个具有特定值的指针。虽然,我不明白为什么我会比平常多得多。我问了几个人,我被告知我得到一个子字符串?为什么我会返回一系列指针返回类型的字符?
问题:我输入单词hotdog。 我期望在索引[2]处返回一个指针。相反,我得到了chars狗。这是为什么?我将如何获得索引[2]?我正在考虑解除引用它,但是我在获取返回类型时遇到问题。
我无法更改我的函数的返回类型或参数。
#include <iostream>
char * GetValueAtIndex(char * const c, int index);
void ReadString(char * c, int length);
int main()
{
const int size = 10;
char ma[size];
char * pointer = ma;
ReadString(ma, 20);
std::cout << GetValueAtIndex(pointer, 3) << std::endl;
system("pause");
}
void ReadString(char * c, int length)
{
std::cin.getline(c, length);
}
char * GetValueAtIndex(char * const c, int index)
{
return c + index;
}
为什么你期望指数[2 ]? GetValueAtIndex使用偏移量3,这将是索引[3],并且“热狗”的第四个字母是'd',所以我期望输出为'狗' –