gpt4 book ai didi

ios - 无法在结构中传递C字符串

转载 作者:行者123 更新时间:2023-12-01 19:12:42 25 4
gpt4 key购买 nike

我在从传递的结构中获取char *字符串时遇到麻烦。我有以下代码:

typedef struct {
NSInteger id;
char *title;
} Movie;

...

Movie movie = [self randomMovie];

NSInteger movieID = movie.id;
NSString *movieTitle = [NSString stringWithUTF8String:movie.title];
NSLog(@"movieTitle: %@", movieTitle);

...

- (Movie)randomMovie {
sqlite3_stmt *statement;
NSString *query = @"SELECT id, title FROM movies ORDER BY RANDOM() LIMIT 1;";

Movie movie;

if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_ROW) {
// Get the id and title of the first
movie.id = sqlite3_column_int(statement, 0);
movie.title = (char *)sqlite3_column_text(statement, 1);
}
}

NSLog(@"Random movie %d title: %@", movie.id, [NSString stringWithUTF8String:movie.title]);

sqlite3_finalize(statement);
return movie;
}

这给了我输出:
2013-03-13 10:10:39.438 Fabflix[89156:c07] Random movie 872011 title: Ray
2013-03-13 10:10:39.439 Fabflix[89156:c07] movieTitle: (null)

有谁知道为什么没有从randomMovie正确传递标题字符串?谢谢!

最佳答案

我对sqlite3 C API并不十分熟悉,但是您确定sqlite3_finalize()调用不会破坏sqlite3_column_text()返回的C字符串吗?您可能需要对该事物进行strdup()(然后记住,稍后再对其进行free())。

:从文档中更新:是的:

返回的指针有效,直到如上所述发生类型转换,或者直到调用sqlite3_step()或sqlite3_reset()或sqlite3_finalize()为止。用于保存字符串和BLOB的内存空间会自动释放。

关于ios - 无法在结构中传递C字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com