假设我有一个指针char *a
。在C中的struct中分配一个指针?
而且
struct b {
unsigned short num;
unsigned short size;
unsigned char *a;};
我应该如何分配的东西 'A' 在这种情况下? 谢谢。
假设我有一个指针char *a
。在C中的struct中分配一个指针?
而且
struct b {
unsigned short num;
unsigned short size;
unsigned char *a;};
我应该如何分配的东西 'A' 在这种情况下? 谢谢。
取决于。你想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);
其中lengthOfA
为strlen(a)
,如果你有一个空结尾的字符串。
我已动态分配内存并分配给pointer a
。 struct b
类型的
#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;
声明变量,然后指向a
到现有的存储位置,或者其使用malloc
struct b buf;
buf.a = (unsigned char *)malloc(YOUR_SIZE_IN_BYTE); // allocated memory for a
// fill content into a here
可以在一个以上的方式分配用于分配存储器
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.当初始化可以使用一个字符串literral
struct b t2 = {0,4,"hey"};
这要看是什么意思'结构B'。 – BLUEPIXY