gpt4 book ai didi

c - 如何更改 C 中结构属性的大小?

转载 作者:太空宇宙 更新时间:2023-11-04 08:06:15 25 4
gpt4 key购买 nike

我是 C 编程的新手,我需要创建一个电话簿。每个条目必须有姓名、电话号码和注释部分。问题是注释部分的大小应该可以根据输入进行更改。例如,如果用户输入一个包含 30 个字符的字符串,则注释的大小应为 30。我不知道该怎么做。

到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <note>

struct Entries {
char name[50];
char phoneNumber[11];
char * note;
note = (char *)malloc(5*sizeof(char));
}Entries;

int main()
{
int command;
int counter = 0;
char tempNote[50];
char tempName[50];
char tempPhoneNumber[11];

while(1){
printf("Welcome to myPhoneBook! Please select an option:\n 1) New entry\n 2) List all entries\n 3) Edit\n 4) Delete\n 5) Search\n");
scanf("%d", &command);

if(command == 1){
struct Entries entry;

printf( "Enter a name:\n");
scanf("%s",tempName);
strcpy(entry.name, tempName);

printf( "Enter a phone:\n");
scanf("%s",tempPhoneNumber);
strcpy(entry.phoneNumber, tempPhoneNumber);

printf( "Enter a note:\n");
scanf("%s",tempNote);
entry.note = (char *)realloc(entry.note,strlen(tempNote));
strcpy(entry.note, tempNote);

counter++;
}
}
return 0;
}

当用户第一次输入姓名、电话号码和备注时,程序会自动停止工作,尽管它本应要求永远使用这些属性。

最佳答案

您可以使用 flexible array member .这是更好的方法。

引用自 C11 标准,章节 §6.7.2.1

[...] the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply. However, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.

和例子

EXAMPLE 2 After the declaration:

  struct s { int n; double d[]; };

the structure struct s has a flexible array member d. A typical way to use this is:

int m = /* some value */;

struct s *p = malloc(sizeof (struct s) + sizeof (double [m]));

and assuming that the call to malloc succeeds, the object pointed to by p behaves, for most purposes, as if p had been declared as:

struct { int n; double d[m]; } *p;

现在,按照上面的步骤,您可以扫描输入,使用输入长度作为 m,然后分配足够的内存来保存输入。

关于c - 如何更改 C 中结构属性的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42702994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com