-1

嘿,我是 C 语言的新手程序员,不明白我在程序中遇到的这些错误。有人可以向我解释我的代码有什么问题以及修复它的方法。我很想学习这个。感谢任何帮助。

编译器消息:

gcc project1shell.c
project1shell.c: In function ‘main’:
project1shell.c:55:8: warning: passing argument 1 of ‘hello’ makes pointer from integer without a cast [enabled by default]
project1shell.c:16:6: note: expected ‘char *’ but argument is of type ‘char’
project1shell.c:62:8: warning: passing argument 1 of ‘forkk’ makes pointer from integer     without a cast [enabled by default]
project1shell.c:18:6: note: expected ‘char *’ but argument is of type ‘char’

我的代码:

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

#define CHILD 0
#define SIZE 256

char hello(char command[SIZE]);
void forkk(char command[SIZE]);
void exitt(char command[SIZE]);

/////////////////////////////

int main(void) {

/* variable delcarations */
char command[SIZE]="";
char buffer[SIZE]="";

/////////////////////////////

    /**** prompt the user with the program ****/
    printf("*** Welcome to LJ's Shell! ***\n\n");

    /**** implements exit and commands ****/
    while(1) {
       if (strcmp(command, "exit") == 0) {
          break;
       }
       hello(command[SIZE]);

       //prompt(command[SIZE], buffer[SIZE]);
       printf("nshell:~$ ");
       fgets(buffer, sizeof(buffer), stdin);
       sscanf(buffer, "%s", command);

       forkk(command[SIZE]);
    }

}


///////// Functions //////////

/************ fork process **************/
void forkk(char command[SIZE]) {
    int pid = 0;
    int childvalue = 0;

    if (strcmp(command, "fork") == 0) {

       pid = fork();

       if (pid != CHILD) {   /* this is the parent */
           printf("I am the parent.  Ready to wait on the child.\n");
           pid = waitpid(-1, &childvalue, 0);
           printf("Child %d returned a value of %x in hex.\n", pid, childvalue);
           return;
       }
       else {  /* this is the child */
           printf("I am the child.\n");
           exit(2);
       }
    }
}

/***************** exit *******************/

void exitt(char command[SIZE]) {
    if (strcmp(command, "exit") == 0) {
       exit(0);
    }
}

/************* Hello Test ****************/
char hello(char command[SIZE]) {
    if (strcmp(command, "hello") == 0) {
    printf("Hello there!\n");
    //reset command back to ""
    }
}
4

2 回答 2

0

您可能应该重新审视数组语法。

调用时您所做的是获取命令数组之后hello(command[SIZE])的字符(最后一个有效索引是),并将其传递给 hello 函数,该函数需要将此 char 值(有符号整数)转换为指针。SIZE - 1

编译器发现有问题,并发出警告。

我不太清楚为什么你sscanf()刚刚得到的缓冲区fgets(),你可以很容易地fscanf("%256s")stdin

于 2013-09-18T05:09:12.327 回答
0

改变

hello(command[SIZE]);

hello(command);

这同样适用于forkk(command[SIZE]);。这应该可以解决编译问题。

问题是,command是一个数组,command[n]而是一个元素。而且访问是非法的,command[SIZE]因为数组只有 SIZE - 1 个元素。

于 2013-09-18T05:06:37.973 回答