我在这里和编程领域都是新手。我的问题是,当我尝试为数组指针结构的属性赋值时,它不起作用。以下没有结构工作的代码:
#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]);
}
}
但是当我放置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)
}
}
为什么会这样? 对不起,如果我是新来的人。
谢谢,以下代码可以正常工作:
#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);
}
答案 0 :(得分:0)
首先,在这里
personArray = (Person *)malloc(sizeof(int) * size);
您可能希望使用sizeof(Person)
而不是sizeof(int)
。此外,您似乎对char
和字符串有些困惑。这是这里:
unsigned char name = "Person_name";
尝试将字符串文字分配给char
。您的编译器应发出警告。而是应为unsigned char *name
。并将name
中的Person
用作指针。另请注意,这不会复制。如果要复制字符串,请执行以下操作:
unsigned char *name = "Person_name";
personArray[i].name = malloc(strlen(name) + 1);
strcpy(personArray[i].name, name);
如果这样做,请在使用完字符串后将其释放,例如在打印后:
free(personArray[i].name);
(无论哪种方式)完成后,请不要忘记释放personArray
的内存:
free(personArray);