简体   繁体   English

访问结构内的char指针的各个元素

[英]Accessing individual elements of char pointer inside a struct

I have a struct defined as 我有一个结构定义为

typedef struct {
char *somechar;
} Random;

I instantiate a struct like this - 我实例化一个这样的结构-

Random *r=(Random *)malloc(sizeof(Random));

How to individually assign characters one by one to somechar? 如何分别将字符逐一分配给somechar? I"ve used 我用过

r->somechar+0='b';
r->somechar+1='a';

and this doesn't work. 这是行不通的。

First of all you need to allocate the data pointed by char* somechar : you are allocating space for the struct which contains the pointer, not the pointed data. 首先,您需要分配char* somechar指向的数据:您正在为包含指针而不是指向的数据的struct分配空间。 You need to allocate it separately 您需要单独分配

Random *r = malloc(sizeof(Random));
r->somechar = malloc(20); // allocate space for 20 characters

Mind that you don't need to cast the result of malloc since in C a void* can implicitly be converted to any other pointer type. 请注意,您不需要转换malloc的结果,因为在C中, void*可以隐式转换为任何其他指针类型。 In addition you must make sure that the value returned by malloc is a valid address (hence it's != NULL ) to be sure that the heap allocation didn't fail. 另外,您必须确保malloc返回的值是一个有效地址(因此它是!= NULL ),以确保堆分配不会失败。

Finally to access the individual elements of the char* you have two options: 最后,要访问char*的各个元素,您有两个选择:

  • using the correct index access operator, so r->somechar[1] = .. 使用正确的索引访问运算符,因此r->somechar[1] = ..
  • using pointer arithmetic directly, *(r->somechar+1) = .. 直接使用指针算法, *(r->somechar+1) = ..

The latter is similar to what you were trying but you need to use the dereference * operator to tell the compiler that you want to assign to the value pointed by the address. 后者与您尝试的类似,但是您需要使用dereference *运算符告诉编译器您要分配给该地址指向的值。

Don't forget that you need to deallocate memory too, for both somechar and r by calling free(r->somechar) and free(r) . 不要忘记,您也需要通过调用free(r->somechar)free(r)来为somecharr释放内存。

typedef struct {
    char *somechar;
} Random;

Requires first to allocate the struct itself: 首先需要分配结构本身:

Random *r = malloc(sizeof(*r));

and then an array somechar has to point to. 然后数组必须指向somechar Without this, it will be uninitialized, invoking undefined behaviour if you dereference it. 没有此功能,它将被取消初始化,如果您取消引用它,则会调用未定义的行为

r->somechar = malloc(MAX_ARRAY_LENGTH);

MAX_ARRAY_LENGTH has to be set to the max. MAX_ARRAY_LENGTH必须设置为最大值。 number of entries you want to store into that char array. 您要存储到该char数组中的条目数。 As sizeof(char) is defined 1 by the standard, no need to specify this explicitly. 由于sizeof(char)由标准定义为1 ,因此无需显式指定。

Note that you should not cast void * as returned by malloc & friends. 请注意,您不应将malloc和friends返回的void *void * Whoever tells you should read here . 谁告诉你应该在这里阅读。

Caution: 警告:

  • Always check the result of system functions. 始终检查系统功能的结果。 malloc can fail, returning a null pointer . malloc可能失败,返回空指针 Dereferencing such is undefined behaviour and can make your program crash - if you are lucky (if not, you will not notice anything, but get strange behaviour - like nasal demons ). 取消引用是未定义的行为,并且可能会使您的程序崩溃-如果您幸运的话(否则,您将不会注意到任何东西,但会得到奇怪的行为-如鼻恶魔 )。
  • If you want to store a C-string in that char array, account for the trailing '\\' 如果要将C字符串存储在该char数组中,请在结尾加上'\\'
  • Note that all malloc ed memory is uninitialized. 请注意,所有已malloc内存都未初始化。 If you want zeroed memory, use calloc . 如果要将内存清零,请使用calloc
  • free both allocated blocks! free两个分配的块! Use the reverse order of allocation. 使用相反的分配顺序。

If using C99 or C11 (recent standard), you can use a flexible array member and avoid the second allocation: 如果使用C99或C11(最新标准),则可以使用灵活的数组成员,并避免第二次分配:

typedef struct {
    char somechar[];    // must be last member of the struct
} Random;

...

Random *r = malloc(sizeof(*r) + MAX_ARRAY_LENGTH);

This will allocate the struct with the array of the given size in a single block. 这将在单个块中为结构分配给定大小的数组。

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

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