C语言 如何通过引用在函数内部初始化struct数组成员



我试图使结构数组和初始化结构数组成员,但我不知道如何访问结构成员,我使用(st->ch)[t] = 'c';和其他类似的语法,但我没有成功。

致以最亲切的问候。

struct ST
{
char ch;
};
bool init(ST* st, int num)
{
st = (ST*)malloc(num * sizeof(ST));
if (st == NULL) return false;
for (int t = 0; t < num; t++) (st->ch)[t] = 'c';
return true;
}
int main()
{
ST* s = NULL;
init(s, 2);
putchar(s[1].ch);
}

你在main中声明了一个指针

ST* s = NULL;

在C中应该像

那样声明
struct ST* s = NULL;

因为您声明了类型说明符struct ST(在C中与ST不同)

struct ST
{
char ch;
};

,您将在函数中更改。要做到这一点,你必须通过引用将指针传递给函数。也就是函数声明至少看起来像

bool init( struct ST **st, int num );

函数像

一样被调用
init( &s, 2);
if ( s ) putchar( s[1].ch );

函数本身可以定义为

bool init( struct ST **st, int num )
{
*st = malloc( num * sizeof( struct ST ) );
if ( *st )
{
for ( int i = 0; i < num; i++) ( *st )[i].ch = 'c';
}
return *st != NULL;
}

如果您使用c++编译器,则替换此语句

*st = malloc( num * sizeof( struct ST ) );

*st = ( struct ST * )malloc( num * sizeof( struct ST ) );

当不再需要结构数组时,应该释放数组占用的内存,如

free( s );

可以通过以下方式访问struct成员:

st[t].ch

正如@kaylum所提到的stinit()中的局部变量,并且不更新主函数中的变量s,因此另一种选择可以是您将变量s的地址添加给init(),或者可以返回分配的内存,如下面的代码片段所示。而不是使用bool作为返回类型来检查,你可以使用ST*作为返回类型,如果它返回NULL或mem地址来获取mem分配状态。

另外,你必须对typedef struct ST ST;结构体进行类型定义,以便能够直接使用ST类型,否则你必须坚持使用struct ST

typedef struct ST
{
char ch;
}ST;
ST* init(int num)
{
ST *st;
// Create num elems of ST type
st = (ST*)malloc(num * sizeof(ST));
// return NULL is st unintialised
if (st == NULL) {
return st;
}
// Assign ch member variable of the 't'th st element wit 'c'
for (int t = 0; t < num; t++) {
st[t].ch = 'c';
}
return st;
}
int main()
{
ST* s;
// creates an array of size two of type st
s = init(2);
putchar(s[1].ch);
return 0;
}

最新更新