【问题标题】:initialize object adress from a function [duplicate]从函数初始化对象地址[重复]
【发布时间】:2013-06-12 10:04:36
【问题描述】:

您能帮我理解如何从函数中更新指针地址吗?

我在我的 C++ 项目中使用了一个 C 库 (libmpdclient)。

来自 C 库:

const struct mpd_song *     mpd_entity_get_song (const struct mpd_entity *entity)

我的标题原型:

typedef struct {
  struct mpd_song * m_song; // from a C library
  ....                      // not important stuff
}
void GetSongInfo(const struct mpd_song * m_song, char* uri);

我的代码:

void MpdPlayer::GetSongInfo(const struct mpd_song * song, char* uri)
{
  struct mpd_entity * entity;
  mpd_send_list_meta(m_connection, *uri);
  song = mpd_entity_get_song(entity);
  mpd_entity_free(entity);

  printf("song adress: %p\n", song); // OK the result is 0x370e6e0
  printf("song duration: %u\n", mpd_song_get_duration(song)); // OK I can get the time
}

GetSongInfo(myStruct->m_song, m_fileuri);
printf("myStruct->m_song adress : %p\n", si->m_song); // FAIL the result is : nil

我尝试了这么多认为我迷路了:/

【问题讨论】:

  • 这已经被问了很多很多很多次了。 C 是按值传递。如果要模拟传递引用,则必须使用指针。
  • 已经尝试过了,如果我将“song =”更改为“*song =”我会收到以下错误:不完整类型“const struct mpd_song”的使用无效。但我同意,我自学 C++,但我还是什么都不懂。
  • @userXXXX 提示:您不想更改指针指向的对象。你想改变指针本身。
  • 我觉得我懂的越来越少了……:/

标签: c++ c pointers


【解决方案1】:
struct mpd_song * MpdPlayer::GetSongInfo(char* uri)
{
  struct mpd_entity * entity;
  mpd_send_list_meta(m_connection, *uri);
  struct mpd_song * song = mpd_entity_get_song(entity);
  mpd_entity_free(entity);

  printf("song adress: %p\n", song);
  printf("song duration: %u\n", mpd_song_get_duration(song));

  return song;
}

myStruct->m_song = GetSongInfo(m_fileuri);

【讨论】:

  • 非常感谢 Dialecticus !我仍然对“const”关键字有一些问题,但现在已经解决了;)
  • @mobidyc 注意如果mpd_song 对象在mpd_entity_free 之后有效,则此代码有效。我以为是,但如果不是,那么您必须在调用 mpd_entity_free 之前复制内容。
猜你喜欢
  • 1970-01-01
  • 2012-01-17
  • 2019-10-14
  • 2023-04-02
  • 1970-01-01
  • 2018-09-19
  • 2012-01-02
  • 1970-01-01
  • 2015-12-03
相关资源
最近更新 更多