char []中的内存

时间:2017-12-03 20:32:19

标签: c++ arrays

所以我在c ++ 11工作,这件事发生在我身上:

eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe (Left _) = Nothing
eitherToMaybe (Right x) = Just x

parse' :: Foo0 -> String -> String -> Maybe Bar -- where Foo0 and Bar are the correct types
parse' foo s0 s1 = eitherToMaybe $ parse foo s0 s1

maybeToEither :: a -> Maybe b -> Either a b
maybeToEither x Nothing  = Left x
maybeToEither _ (Just y) = Right y

parseLine :: Text -> IO (Either String Text)
parseLine x = do
  let xStr = convertString x :: String
  let result = asum [
                fileRef <$> parseFile xStr,
                gitDiff <$> parseDiff xStr,
                tagMatch xStr <$ parseTag xStr
               ]
  maybe failure id result
    where parseFile = parse' (parseFileReference) "file reference"
          parseDiff = parse' (parseGitDiffReference) "git diff tag"
          parseTag  = parse' (parsePossibleTag) "possible tag"
          fileRef z = do
                print z
                value <- maybeToEither "Unable to parse" <$> fileReferenceContent z
                return $ (\v' -> "```\n" <> v' <> "```") <$> value
          gitDiff z = do
                print z
                return2x ""
          tagMatch xStr = do
                return (Left $ "Tag that failed to match: " ++ xStr)
          failure = return2x x

我这样做:

char s[100];
strcpy(s, "Andrei");
int n=strlen(Andrei); // (it would be 6)

s [n + 1],... s [n + 8]会发生什么? 如果我去

s[n]='  '; 
s[n+9]='\0';

数组将正常显示。

但如果我指定

cout <<s;

它将打印奇数字符

2 个答案:

答案 0 :(得分:0)

数组元素s[n+1] ... s[n+8]未初始化。据说他们有不确定的价值。尝试输出不确定的值会导致未定义的行为,这意味着任何事情都可能发生。

答案 1 :(得分:0)

所以,你有100个字符的缓冲区。由于C ++中没有严格的初始化策略,因此您获得了BIG SOMETHING的缓冲区。每个应用程序启动之间“大事”的内容会有所不同,可能会因不同的构建模式(调试/发布)等而有所不同。确实,查询“某事”就像试图在随机波上收听广播并听到噪音序列作为回报(每次执行此操作时可能会有所不同)。

运行strcpy会初始化前N个字符,缓冲区的其余部分仍然是“某事”。