繁体   English   中英

在C中的结构内分配指针?

[英]Assigning a pointer inside a struct in C?

假设我有一个指针char *a

struct b {
unsigned short  num;
unsigned short  size;
unsigned char  *a;};

在这种情况下,应如何将材料分配给“ a”? 谢谢。

声明struct b类型的变量,然后将a指向现有的内存位置,或使用malloc为其分配内存

struct b buf;
buf.a = (unsigned char *)malloc(YOUR_SIZE_IN_BYTE);  // allocated memory for a
// fill content into a here

要看。 您是否要foo.a指向a作用? 然后:

struct b foo = ...;
foo.a = a;

或者你想foo.a指向的拷贝a 然后:

struct b foo = ...;
foo.a = malloc(sizeof(char) * lengthOfA);
memcpy(foo.a, a, lengthOfA);

如果您有一个以Null结尾的字符串,则lengthOfAstrlen(a)

我已经动态分配了内存并分配给pointer a

#define EXAMPLE_SIZE 25
main ()
{
struct b sample= { 0, };
sample.a = malloc ( EXAMPLE_SIZE * sizeof (unsigned char) );    
}
b obj;
unsigned char ch = 'F';
obj.a = &ch;

您可以通过多种方式分配

1.动态分配内存(如果需要用户输入)

// you can use realloc also if you want

struct b t1 ;

b.a = malloc(x * sizeof (char) );

//then you can read user from input.

2.虽然初始化可以使用字符串literal

struct b t2 = {0,4,"hey"};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM