将字符数组转换为结构体中的字符串

时间:2022-09-06 10:53:04

I have an array of 4 characters, for example:

我有一个4个字符的数组,例如:

char char_array[10];

char_arr[0] = 'a';
char_arr[1] = 'b';
char_arr[2] = 'c';
char_arr[3] = 'd';
char_arr[4] = '\0';

and I have a structure:

我有一个结构

typedef struct{
int my_int;
char *my_string;
} my_struct_t;

my_struct_t my_struct;  

my_struct.my_string = malloc(10);

I want to assign the char array to the string my_struct.my_string How to I do this? I tried the following:

我想将char数组分配给string _mystruct。my_string如何做这个?我试着以下:

Attempt: 1

my_struct.my_string = malloc(10) 
my_struct.my_string[0] = char_arr[2];
my_struct.my_string[1] = char_arr[2];
my_struct.my_string[2] = '\0';

Attempt: 2

strcpy(my_struct.my_string, char_arr);

Both fail i.e the destination is empty (compilation succeeds). Why does the above fail and how can I overcome this?

我都失败。目标是空的(编译成功)。为什么会失败,我该如何克服呢?

I have both the struct and the char array in stack since I don't want these once I exit the function. I have allocated memory to my_struct.my_string before assigning it.

我在堆栈中有struct和char数组,因为我退出函数后不需要这些。我已经为my_struct分配了内存。my_string之前分配它。

4 个解决方案

#1


1  

You can do it two ways:

你可以用两种方法:

Assign the pointer to the character array

Once the function exits the char_array[10] which the pointer points to will become invalid. The compiler will produce no error, but eventually the program will likely crash because you will overwrite data for another function, or read the wrong data because another function overwrote it with something else. You should google about how the stack works on your computer architecture.

一旦函数退出char_array[10],指针指向的该函数将无效。编译器不会产生错误,但最终程序可能会崩溃,因为您将覆盖另一个函数的数据,或者读取错误的数据,因为另一个函数用其他函数覆盖它。您应该谷歌讨论堆栈如何在您的计算机体系结构上工作。

    char                  char_array[10];
    my_struct_t           var;

    var.my_string = &array[0];

    var.my_string[3] = 'a';

    if (var.my_string[0] == char_array[0])
        printf("See, changes using the pointer effect char_array.\n");
    else
        printf("This will never happen.\n");

Allocate memory and copy the character array

I used for loops to help make it easier to understand exactly how it works. Once the current function exits the pointer will still point to valid memory if you happen to keep it around somehow.

我使用for循环来帮助理解它是如何工作的。一旦当前函数退出,指针仍然指向有效内存。

    char                  char_array[10];
    my_struct_t           var;
    int                   l;

    char_array[0] = 'a';
    char_array[1] = 0;

    // l = strlen(&char_array[0])
    for (l = 0; char_array[l] != 0; ++l);

    var.my_string = (char*)malloc(sizeof(char) * l);

    // strcpy(var.my_string, &char_array[0]);
    for (l = 0; char_array[l] != 0; ++l)
        var.my_string[l] = char_array[l];

    var.my_string[0] = 'a';

    if (var.my_string[0] != char_array[0])
        printf("See, changes using the pointer DO NOT effect char_array.\n");
    else
        printf("This will never happen.\n");

#2


2  

If char_arr is of char[N] type, then malloc array of sizeof(char_arr)/sizeof(char_arr[0]) to my_struct.my_string. And then copy value at each index using strcpy. Finally free when done.

如果char_arr是char[N]类型,那么将sizeof(char_arr)/sizeof(char_arr[0])的malloc数组设置为my_struct.my_string。然后使用strcpy在每个索引处复制值。最后完成后免费。

#3


1  

I assume, you allocate your char_arr on stack, therefore the 1st approach fails. The 2nd approach fails if you don't allocate the memory for the destination. Some of the correct ways are:

我假设,您在堆栈上分配char_arr,因此第一个方法失败。如果没有为目标分配内存,则第二种方法失败。一些正确的方法是:

  1. allocate char_arr on heap and use my_struct.my_string = char_arr, or
  2. 在堆上分配char_arr并使用my_struct。my_string = char_arr,或者
  3. allocate my_string on heap and use strcpy(my_struct.my_string, char_arr)
  4. 在堆上分配my_string并使用strcpy(my_struct)。my_string char_arr)
  5. use strdup, if your compiler supports it.
  6. 如果编译器支持,则使用strdup。

Longer explanation:
You should understand the basics of C memory management. In C, string is just a pointer to a memory chunk. Copying that pointer won't prevent the stack-allocated string to disappear. So, you have to allocate the memory anyway in heap. In order to do this, you either allocate char_arr there (which makes the 1st method valid), or you let the char_arr live on stack, but then you cannot keep the reference to its data (it's going to be destroyed after your current function exits), you need to copy the data to a heap-allocated string. This can be done either manually (with malloc), or using strdup.

更长的解释:您应该了解C内存管理的基础知识。在C语言中,字符串只是内存块的指针。复制该指针不会阻止堆栈分配的字符串消失。所以,你必须在堆中分配内存。为了做到这一点,你要么分配char_arr(这使得第一方法有效),或者你让char_arr住在堆栈,但是你不能保持引用其数据(它会被摧毁后当前函数退出),您需要将数据复制到一个基于堆的字符串。这可以手动(使用malloc)或使用strdup完成。

#4


1  

You need to allocate memory for my_string before storing char_arr into it.

在将char_arr存储到my_string之前,需要为它分配内存。

If you have allocated memory, it should work. This is same as your code (without typedef) and it works fine:

如果您已经分配了内存,那么它应该可以工作。这与您的代码相同(没有typedef),而且它运行良好:

struct my{ int my_int; char *my_string; }p;

结构我{ int my_int;char * my_string;} p;

int main()
{
char char_arr[5];
strcpy(char_arr, "abcd");
p.my_string = (char*) malloc(5);
strcpy(p.my_string, char_arr);
print_string(); //
return 0;
}

print_string()
{
printf("%s",p.my_string);
}

#1


1  

You can do it two ways:

你可以用两种方法:

Assign the pointer to the character array

Once the function exits the char_array[10] which the pointer points to will become invalid. The compiler will produce no error, but eventually the program will likely crash because you will overwrite data for another function, or read the wrong data because another function overwrote it with something else. You should google about how the stack works on your computer architecture.

一旦函数退出char_array[10],指针指向的该函数将无效。编译器不会产生错误,但最终程序可能会崩溃,因为您将覆盖另一个函数的数据,或者读取错误的数据,因为另一个函数用其他函数覆盖它。您应该谷歌讨论堆栈如何在您的计算机体系结构上工作。

    char                  char_array[10];
    my_struct_t           var;

    var.my_string = &array[0];

    var.my_string[3] = 'a';

    if (var.my_string[0] == char_array[0])
        printf("See, changes using the pointer effect char_array.\n");
    else
        printf("This will never happen.\n");

Allocate memory and copy the character array

I used for loops to help make it easier to understand exactly how it works. Once the current function exits the pointer will still point to valid memory if you happen to keep it around somehow.

我使用for循环来帮助理解它是如何工作的。一旦当前函数退出,指针仍然指向有效内存。

    char                  char_array[10];
    my_struct_t           var;
    int                   l;

    char_array[0] = 'a';
    char_array[1] = 0;

    // l = strlen(&char_array[0])
    for (l = 0; char_array[l] != 0; ++l);

    var.my_string = (char*)malloc(sizeof(char) * l);

    // strcpy(var.my_string, &char_array[0]);
    for (l = 0; char_array[l] != 0; ++l)
        var.my_string[l] = char_array[l];

    var.my_string[0] = 'a';

    if (var.my_string[0] != char_array[0])
        printf("See, changes using the pointer DO NOT effect char_array.\n");
    else
        printf("This will never happen.\n");

#2


2  

If char_arr is of char[N] type, then malloc array of sizeof(char_arr)/sizeof(char_arr[0]) to my_struct.my_string. And then copy value at each index using strcpy. Finally free when done.

如果char_arr是char[N]类型,那么将sizeof(char_arr)/sizeof(char_arr[0])的malloc数组设置为my_struct.my_string。然后使用strcpy在每个索引处复制值。最后完成后免费。

#3


1  

I assume, you allocate your char_arr on stack, therefore the 1st approach fails. The 2nd approach fails if you don't allocate the memory for the destination. Some of the correct ways are:

我假设,您在堆栈上分配char_arr,因此第一个方法失败。如果没有为目标分配内存,则第二种方法失败。一些正确的方法是:

  1. allocate char_arr on heap and use my_struct.my_string = char_arr, or
  2. 在堆上分配char_arr并使用my_struct。my_string = char_arr,或者
  3. allocate my_string on heap and use strcpy(my_struct.my_string, char_arr)
  4. 在堆上分配my_string并使用strcpy(my_struct)。my_string char_arr)
  5. use strdup, if your compiler supports it.
  6. 如果编译器支持,则使用strdup。

Longer explanation:
You should understand the basics of C memory management. In C, string is just a pointer to a memory chunk. Copying that pointer won't prevent the stack-allocated string to disappear. So, you have to allocate the memory anyway in heap. In order to do this, you either allocate char_arr there (which makes the 1st method valid), or you let the char_arr live on stack, but then you cannot keep the reference to its data (it's going to be destroyed after your current function exits), you need to copy the data to a heap-allocated string. This can be done either manually (with malloc), or using strdup.

更长的解释:您应该了解C内存管理的基础知识。在C语言中,字符串只是内存块的指针。复制该指针不会阻止堆栈分配的字符串消失。所以,你必须在堆中分配内存。为了做到这一点,你要么分配char_arr(这使得第一方法有效),或者你让char_arr住在堆栈,但是你不能保持引用其数据(它会被摧毁后当前函数退出),您需要将数据复制到一个基于堆的字符串。这可以手动(使用malloc)或使用strdup完成。

#4


1  

You need to allocate memory for my_string before storing char_arr into it.

在将char_arr存储到my_string之前,需要为它分配内存。

If you have allocated memory, it should work. This is same as your code (without typedef) and it works fine:

如果您已经分配了内存,那么它应该可以工作。这与您的代码相同(没有typedef),而且它运行良好:

struct my{ int my_int; char *my_string; }p;

结构我{ int my_int;char * my_string;} p;

int main()
{
char char_arr[5];
strcpy(char_arr, "abcd");
p.my_string = (char*) malloc(5);
strcpy(p.my_string, char_arr);
print_string(); //
return 0;
}

print_string()
{
printf("%s",p.my_string);
}