我正在使用malloc创建一个结构:
structurePointer = (struct Person*)malloc(sizeof(struct Person));
struct Person
指的是以下类型:
struct Person {
char name;
int age;
}
我目前正在做的加载结构的是:
strcpy(&(structurePointer -> name), names);
names只是一个指向数组元素的指针,该元素是某个名称,我传递给包含上述代码的函数。 比加载年龄:
structurePointer + 1 -> age = ages;
虽然添加1会感觉不对,因为添加1会指向下一个32位或16位的开头,具体取决于架构?如果这是这样做的方法,我不会理解编译器如何通过添加1知道结构的age变量的起始地址的位置,因为显然name变量是char类型所以它将是任意大小?
谢谢我需要创建一个指向结构的指针数组,所以我假设每个数组元素都有名称的起始地址,而不是使用它来打印结构,我可以通过添加1来打印年龄?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HOW_MANY 7
//pointer declaration required?
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John",
"Tim", "Harriet"};
//pointer as it is an array
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
struct Person {
char name;
int age;
}; //struct-person
//elements in the array consists of the struct Person type
struct Person *people[7];
//passing the pointer to the struct Person array
static void insert(struct Person *people[], char *names, int ages)
{
struct Person *structurePointer;
structurePointer = (struct Person*)malloc(sizeof(30));
int incrementVar = 0;
strcpy(&(structurePointer-> name), names); //
people[incrementVar]= structurePointer;
structurePointer -> age = ages;
incrementVar++;
} //insert-method
int main(int argc, char **argv)
{
struct Person *people[7];
for (int i = 0; i <= HOW_MANY - 1; i++) {
//passing name as a pointer as it has
insert (people, names[i], ages[i]);
}
for (int i = 0; i <= HOW_MANY - 1; i++) {
printf("%d ", people[i]-> age);
printf("%s", &(people[i] -> name));
printf("\n");
}
return 0;
} //main
答案 0 :(得分:2)
你的小代码有很多问题,
您调用了一个不成功的函数strpy()
您声称使用的语法无效,因为1->
肯定会成为编译错误。
在我看来,你需要学习更多。要在正确分配空间的情况下访问结构元素,只需使用->
运算符,例如
struct Person {
char name[100]; // Be careful with array bounds here
int age;
}
struct Person *person = malloc(sizeof *person);
if (person != NULL) {
strcpy(person->name, "your name");
person->age = 33;
}
答案 1 :(得分:0)
关于:
structurePointer + 1 -> age = ages;
这是错的。
你真正想要记住的是,向指针添加一个值会使指针增加指针类型中的字节数(在本例中为sizeof(struct Person))
请记住,->
运算符的优先级高于+
运算符,因此操作顺序不正确。
建议使用:
structurePointer->age = ages;