访问/修改结构中的字符串数组
假设我有以下代码:
typedef struct
{
char **p;
} STRUCT;
int main()
{
STRUCT s;
*(s.p) = "hello";
printf("%s\n", *(s.p));
return 0;
}
这显然不起作用,但它应该显示我想要做什么。我将如何初始化、访问、打印结构中的字符串数组等?
Suppose I have the following code:
typedef struct
{
char **p;
} STRUCT;
int main()
{
STRUCT s;
*(s.p) = "hello";
printf("%s\n", *(s.p));
return 0;
}
which obviously doesn't work, but it should show what I want to do. How would I go about initialising, accessing, printing, etc the array of strings in the structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想,你有两个
*
而你只需要一个。尝试:如果您确实想要双重间接寻址,则需要为要取消引用的指针分配一些空间。原始程序中的
*(sp)
取消引用未初始化的指针。在这种情况下:第二个程序只为一个字符串指针分配空间;如果你想要一个数组,只需分配适当的空间即可。
You have two
*
where you want just one, I think. Try:If you do really want to have the double indirection, you need to allocate some space for the pointer you're dereferencing.
*(s.p)
in your original program dereferences an uninitialized pointer. In this case:This second program allocates space for just one string pointer; if you want an array, just allocate the appropriate amount of space.
目前没有数组,但我假设您想创建一个。您需要首先分配您想要的字符串数量的 char * :
There is no array at the moment, but I assume you want to create one. You need to first allocate as many
char *
s as you want strings:您需要通过向结构添加计数成员或使用 NULL 标记值来了解数组中包含多少个字符串。以下示例使用 NULL 标记:
分配和初始化:
获取
number_of_strings
、length_of_ith_string
和ith_string
的适当值。访问/打印:
解除分配:
You're going to need to know how many strings are contained in the array, either by adding a count member to the struct or by using a NULL sentinel value. The following examples use the NULL sentinel:
Allocating and initializing:
for appropriate values of
number_of_strings
,length_of_ith_string
, andith_string
.Accessing/printing:
Deallocating: