免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1480 | 回复: 2
打印 上一主题 下一主题

关于K&R上指针数组一节的一个问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-04-06 13:44 |只看该作者 |倒序浏览
K&R第5。5节的一段程序是个unix中函数sort的简化版本,就是对输入文本排序:
#include <stdio.h>
#include <string.h>

#define MAXLINES 5000

char *lineptr[MAXLINES];

int readlines (char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

void qsort(char *lineptr[], int left, int right);

main()
{
        int nlines;
       
        if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
                qsort(lineptr, 0, nlines-1);
                writelines(lineptr, nlines);
                return 0;
        } else {
                printf("error: input too big to sort\n");
                return 1;
        }
}

#define MAXLEN 1000
int getline(char *, int);
char *alloc(int);

int readlines(char *lineptr[], int maxlines)
{
        int len, nlines;
        char *p, line[MAXLEN];
        nlines = 0;
        while ((len = getline(line, MAXLEN)) > 0)
                if (nlines >- maxlines || (p = alloc(len)) == NULL)
                        return -1;
                else {
                        line[len-1] = '\0';
                        strcpy(p, line);
                        lineptr[nlines++] = p;
                }
        return nlines;
}

void writelines(char *lineptr[], int nlines)
{
        while (nlines-- > 0)
                printf("%s\n", *lineptr++);
}
还有一个qsort函数省略了,就是快速排序
这段代码这段代码中关于指针数组lineptr,有个问题,就是在writelines中用到了*lineptr++也就是将数组名当作指针来用了,虽然它是个指针数组但lineptr也是数组名阿,在5.3中又说过数组名不是变量,虽然它表示一个地址但不能对其赋值和作lineptr++这样的运算,那这样说不是这两处矛盾了吗??请教高手指教!!谢谢!!!

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
2 [报告]
发表于 2007-04-06 14:48 |只看该作者
When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.

这是你看得书前面的一句话。
看书要仔细呀。

论坛徽章:
0
3 [报告]
发表于 2007-04-06 15:13 |只看该作者
谢谢斑竹!!呵呵,是的是的,偶的英文水平还不行阿,有时候还不能完全理解作者的意思,现在是看明白了,调用函数中的数组名传递给被调用函数的只是一个数组首地址副本,被调用函数将它看作一个指针变量!!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP