2014-02-12 23 views
0

假设我有一个指针char *a在C中的struct中分配一个指针?

而且

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

我应该如何分配的东西 'A' 在这种情况下? 谢谢。

+0

这要看是什么意思'结构B'。 – BLUEPIXY

回答

0

取决于。你想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); 

其中lengthOfAstrlen(a),如果你有一个空结尾的字符串。

0

我已动态分配内存并分配给pointer astruct b类型的

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

声明变量,然后指向a到现有的存储位置,或者其使用malloc

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

可以在一个以上的方式分配用于分配存储器

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"};