【发布时间】:2017-10-14 20:49:03
【问题描述】:
我对 C 语言相当陌生,我很难掌握所有这些指针。换句话说,取消引用运算符和 & 号运算符。我相信,在盯着它们看了一会儿之后,我开始了解它们是如何工作的。例如:
int x = 1; //this creates an integer variable called x and assigns one to it
int *pointer; //this creates a pointer variable that will point to an integer
pointer = &x; //now the variable pointer points to x
*pointer = 0 //the value that pointer points to is now zero
我很确定我了解它的工作原理。
我正在阅读 Kernighan 和 Ritchie 的“The C Programming Language”,但我对他们在第 5.4 节(地址算术)中的一些代码感到困惑。我应该指出,我了解地址算术,所以我的问题与此无关。我对以下函数中的代码的问题也不是。在线搜索有关此代码的问题会产生很多帖子,其中人们不了解 if/else 语句中的代码如何运行。无论如何,我的问题是关于函数名本身。
#define ALLOCSIZE 1000
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
char *alloc(int n) /*return pointer to n charachters*/
{
if (allocbuf + ALLOCSIZE - allocp >=n)
{
allocp += n;
return allocp - n;
}
else
return 0;
}
再次,我理解函数中的代码,但如何理解
*alloc
工作?我知道这个函数返回一个指针。这是否意味着通过将函数名作为指针,我们将返回指向 char 类型的指针?如果是这样,它指向什么?在我之前的示例中,我们有
int x = 1;
int *pointer;
pointer = &x;
这里的变量“pointer”指向x变量。然而。在函数 alloc 中没有指向任何东西。任何帮助将不胜感激。
【问题讨论】:
-
但是
char *allocp是一个指针,它指向allocbuf。这里解释了“失踪”&Is an array name a pointer?