[英]Assign to an element of a struct of a pointer array don't work (null)
I'm new here and in programming.我是新来的,在编程。 My problem is when i try to asign a value to a proprerty of a array pointers struct, it does not work.
我的问题是当我尝试为数组指针结构的属性赋值时,它不起作用。 The following code without struct work:
下面没有结构体的代码可以工作:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array;
int size = 10;
array = malloc(sizeof(int) * size);
int i;
for (i = 0; i < size; i++)
{
array[i] = i * i;
}
for (i = 0; i < size; i++)
{
printf("%d\n", array[i]);
}
}
But when i put struct it does print (null):但是当我放入 struct 时,它确实会打印(空):
#include <stdio.h>
#include <stdlib.h>
typedef struct Person
{
unsigned char name;
} Person;
int main()
{
Person *personArray;
int size = 10;
personArray = (Person *)malloc(sizeof(int) * size);
int i;
for (i = 0; i < size; i++)
{
unsigned char name = "Person_name"; //[Warning] initialization makes integer from pointer without a cast
personArray[i].name = name;
}
for (i = 0; i < size; i++)
{
printf("%s\n", personArray[i].name); //Print (null)
}
}
Why this happens?为什么会发生这种情况? Sorry for anything if I'm new here.
对不起,如果我是新来的。
Thank you, the following code work:谢谢,以下代码有效:
#include <stdio.h>
#include <stdlib.h>
typedef struct Person
{
unsigned char *name;
} Person;
int main()
{
Person *personArray;
int size = 10;
personArray = (Person *)malloc(sizeof(Person) * size);
int i;
for (i = 0; i < size; i++)
{
unsigned char *name = "Person_name";
personArray[i].name = malloc(strlen(name) + 1); //[Warning] incompatible implicit declaration of built-in function 'strlen'
strcpy(personArray[i].name, name); //[Warning] incompatible implicit declaration of built-in function 'strcpy'
}
for (i = 0; i < size; i++)
{
printf("%s\n", personArray[i].name);
free(personArray[i].name);
}
free(personArray);
}
First of all, here首先,这里
personArray = (Person *)malloc(sizeof(int) * size);
You probably want sizeof(Person)
instead of sizeof(int)
.您可能需要
sizeof(Person)
而不是sizeof(int)
。 Furthermore, you seem to have some confusion with char
and strings.此外,您似乎对
char
和字符串有些困惑。 This here:这里:
unsigned char name = "Person_name";
Attempts to assign a string literal to a char
.尝试将字符串文字分配给
char
。 Your compiler should issue a warning.您的编译器应该发出警告。 Instead this should be
unsigned char *name
.相反,这应该是
unsigned char *name
。 And also make the name
in Person
a pointer.并且还将
Person
的name
Person
指针。 Also note that this makes no copy.另请注意,这不会复制。 If you wanted a copy of the strings, do this instead:
如果您想要字符串的副本,请改为执行以下操作:
unsigned char *name = "Person_name";
personArray[i].name = malloc(strlen(name) + 1);
strcpy(personArray[i].name, name);
If you do this, free the string when you're done using it, such as after you print it:如果这样做,请在使用完字符串后释放字符串,例如在打印后:
free(personArray[i].name);
And (either way) when you're done, don't forget to free the memory of personArray
:并且(无论哪种方式)完成后,不要忘记释放
personArray
的内存:
free(personArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.