You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UnsafeMutablePointer从缓冲区首次读取后被释放导致字符统计结果异常的问题求助

UnsafeMutablePointer从缓冲区首次读取后被释放导致字符统计结果异常的问题求助

各位好,我最近在写一个统计字符串中连续重复字符出现次数的小功能,目标是把字符串 "aaabbbdccccc" 处理成 ["a": 3, "b": 4, "c": 5] 这样的字典结果,但运行自己写的代码后,最终得到的结果居然只有 ["a": 1],完全和预期不符。

先贴一下我的代码:

let string = "aaabbbdccccc"
var pointer = string.withCString { UnsafeMutablePointer<Int8>(mutating: $0) }
var currentChar = pointer.pointee
var count = 1
pointer = pointer.successor()
var values = [String: Int]()

while currentChar != 0 {
    print(currentChar)
    if currentChar == pointer.pointee {
        count += 1
    } else {
        let charString = String(UnicodeScalar(UInt8(currentChar)))
        values[charString] = count
        count = 1
        currentChar = pointer.pointee
    }
    pointer = pointer.successor()
}

我现在完全搞不懂哪里出了问题,调试的时候发现循环好像没正常走完,最终就只统计了第一个字符的一次出现。我自己猜会不会是withCString的作用域问题?是不是闭包执行完之后,它生成的C字符串缓冲区就被释放了,后面我用指针去访问的都是已经被回收的内存,导致指针操作异常了?

有没有大佬能帮我看看问题出在哪,怎么修改才能得到正确的统计结果啊?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:08:07