免费注册 查看新帖 |

Chinaunix

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

为什么这里用字符数组可以,用字符指针就没输出? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-04-26 14:40 |只看该作者 |倒序浏览
从教课书考了一个程序, 只把变量BUF从 CHAR   BUF[1024]改为CHAR   *BUF, 为啥程序能运行,却无输出了呢:  先谢谢了:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

main()
{
    char buf[1024];            《----------
    char *args[64];

    for (; {
        /*
         * Prompt for and read a command.
         */
        printf("Command: ";

        if (gets(buf) == NULL) {
            printf("\n";
            exit(0);
        }

        /*
         * Split the string into arguments.
         */
        parse(buf, args);

        /*
         * Execute the command.
         */
        execute(args);
    }
}

/*
* parse--split the command in buf into
*         individual arguments.
*/
parse(buf, args)
char *buf;
char **args;
{
    while (*buf != NULL) {
        /*
         * Strip whitespace.  Use nulls, so
         * that the previous argument is terminated
         * automatically.
         */
        while ((*buf == ' ') || (*buf == '\t'))
            *buf++ = NULL;

        /*
         * Save the argument.
         */
        *args++ = buf;

        /*
         * Skip over the argument.
         */
        while ((*buf != NULL) && (*buf != ' ') && (*buf != '\t'))
            buf++;
    }

    *args = NULL;
}

/*
* execute--spawn a child process and execute
*           the program.
*/
execute(args)
char **args;
{
    int pid, status;

    /*
     * Get a child process.
     */
    if ((pid = fork()) < 0) {
        perror("fork";
        exit(1);

    }

    /*
     * The child executes the code inside the if.
     */
    if (pid == 0) {
        execvp(*args, args);
        perror(*args);
        exit(1);

      }

    /*
     * The parent executes the wait.
     */
    while (wait(&status) != pid)
        /* empty */ ;
}

论坛徽章:
0
2 [报告]
发表于 2006-04-26 15:02 |只看该作者
原帖由 huniu 于 2006-4-26 14:40 发表
从教课书考了一个程序, 只把变量BUF从 CHAR   BUF[1024]改为CHAR   *BUF, 为啥程序能运行,却无输出了呢:  先谢谢了:

char buf[1024];  


改成 char *buf 是會發生一些錯誤,因為你沒有配置一塊內存空間 (memory) 供程式使用。

要這樣寫請使用 malloc() 先配置一塊 buffer 給程式使用。ex

  1. buf = (char *) malloc(sizeof(char) * 1024)
复制代码


記得最後要釋放該區塊。

  1. free(buf)
复制代码


==

论坛徽章:
0
3 [报告]
发表于 2006-04-26 15:12 |只看该作者

非常感谢你的帮助,咱这就试试。

非常感谢你的帮助,咱这就试试。

论坛徽章:
0
4 [报告]
发表于 2006-05-04 10:01 |只看该作者
同意kenduest     不过huniu 下次贴代码请用其所长code功能这样大家会好看一点

论坛徽章:
0
5 [报告]
发表于 2006-05-05 13:11 |只看该作者
偶也经常犯这样的错误

论坛徽章:
0
6 [报告]
发表于 2006-05-06 22:36 |只看该作者
指针不分配空间,run-》core
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP