我知道这个问题已经存在了一段时间,但我发现答案有点模糊、冗长和/或令人困惑;因此,我将特别提到我的代码,以便充分理解重点。
所以我有这个结构:
typedef struct album {
unsigned int year;
char *artist;
char *title;
char **songs;
int songs_c;
} album ;
以下是相关功能:
struct album* init_album(char *artist, char *album, unsigned int year){
struct album *a;
a= malloc( sizeof(struct album) );
a->artist = malloc( strlen(artist) + 1);
strncpy(a->artist, artist, strlen(artist));
a->title = malloc( strlen(album) + 1);
strncpy(a->title, album, strlen(album));
a->year = year;
return a;
}
void add_song(struct album *a, char *song){
int index = a->songs_c;
if (index == 0){
a->songs = malloc( strlen(song) );
} else a->songs[index] = malloc( strlen(song)+1 );
strncpy(a->songs[index], song, strlen(song));
a->songs_c= a->songs_c+1;
}
还有一个主函数:
int main(void){
char *name;
char artist[20] = "The doors";
char album[20] = "People are strange";
int year = 1979;
struct album *a;
struct album **albums;
albums = malloc( sizeof(struct album));
albums[0] = init_album((char *)"hihi", (char *)"hoho", 1988);
albums[1] = init_album((char *)"hihi1", (char *)"hoho1", 1911);
printf("%s, %s, %d\n", albums[0]->artist, albums[0]->title, albums[0]->year);
printf("%s, %s, %d\n", albums[1]->artist, albums[1]->title, albums[1]->year);
char song[] = "song 1\0";
add_song(albums[1], song);
free(albums[0]);
free(albums[1]);
}
在“add_song()”中使用strncpy添加歌曲时出现分段错误。
我做错了什么?就像听到的那样,C语言没有“正确”的实现方式,只要它能工作且没有bug,就可以了。但对于初学者来说,获取有关内存分配和复杂数据结构的警告反馈或建议是很好的。
非常感谢! /s
std::string
不会损害你的性能,特别是如果你有一个对象池(甚至是无锁对象池)。 - user405725