我的帖子试图一石二鸟。对于我的疏忽,我要提前道歉。
我正在尝试创建一个字符串数组,我可以使用index[0]或使用ptr++来推进该数组。我不确定是应该创建一个char指针数组,还是应该创建一个指向char数组的指针。这些变量将存储在一个结构中。请原谅我的无知,我只是很难弄清楚何时何地使用()的优先顺序。我理解了一个基本的结构,当我开始松散语法结构时,我开始使用指向字符串的指针。如果我能理解它的语法,我就可以将它进一步应用于数组的维度结构。
假设我对变量的赋值是正确的,我认为对于printf("%s", ptr++)这样的东西,我更喜欢使用ptr++。如果我理解正确的话,ptr++会将指针移动到下一个字符串,或者ptr++的一些形式可以。这是正确的?看起来这对很多很多事情来说都会更快。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Umbrella {
char *name[10];
} Umbrella;
int main ()
{
struct Umbrella * ptr;
// Not understanding this way...
ptr->name[0] = "Some name";
// or this way. Well name++ as long as it wasn't the first string.
ptr->name++ = "Some name";
return 0;
}启动说明:我已经读过Prata的"C Primer Plus“。他在解释事物方面做得很好,只是当你开始按自己的意愿弯曲事物时,你开始不能应用语法。例如,它没有涉及到使用指向结构的指针来访问多维数组,也没有涉及实际使用的语法中的指针算法。有人能推荐另一本书,至少可以通过这样的方法来解决吗?
附言:这是我的第二篇文章,我忘了说我真的很喜欢这个网站的文本输入设计。不得不说:-)。
发布于 2012-12-27 09:44:19
嗯,有一个char *name[10],它实际上就是这样的:
char *name0;
char *name1;
char *name2;
// .. etc作为ptr->name[0]访问它只会选择ptr->name0作为char*。
在这里,ptr->name++ = "asdf";是一个非常糟糕的主意。它主要做的是:
*(ptr->name) = "asdf";
ptr->name += 1;当然,您不能在这里将name加1(它是一个数组,而不是一个指针),所以编译器不允许这样做。
在迭代过去的对象时,++运算符可能很有用。示例:
ptr->name[9] = nullptr; // Make sure the last element is a NULL pointer.
// Take the first element
char **it = ptr->name;
char *current;
// Loop until we reach the NULL
while ((current = *(it++)) != nullptr) {
printf("%s\n", current);
}上面是一种(相当难看的)遍历数组的方式。
在预先分配的数组中插入内容:
char **it = ptr->name; // Start at the first element
*(it++) = "Hi!";
*(it++) = "This is the second message.";
*(it++) = "Hello world!";
*(it++) = nullptr; // End the array当然,所有这些迭代的东西都来自黑暗的过去:现在我们有了C++,它通过std::vector等为我们处理这些事情中的大多数。
https://stackoverflow.com/questions/14048398
复制相似问题