嘿,我是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 ""
}
}
答案 0 :(得分:0)
更改
hello(command[SIZE]);
到
hello(command);
同样适用于forkk(command[SIZE]);
。这应该可以解决编译问题。
问题是,command
是一个数组,而command[n]
是一个元素。访问command[SIZE]
是非法的,因为该数组只有SIZE - 1个元素。
答案 1 :(得分:0)
您应该重新访问数组语法。
当您致电hello(command[SIZE])
时,您要执行的操作是在命令数组(最后一个有效索引为SIZE - 1
)之后取字符,并将其传递给您好function,需要将此char值(有符号整数)转换为指针。
编译器发现可疑,并发出警告。
我不太清楚为什么你sscanf()
来自fgets()
的缓冲区,你可以轻松地fscanf("%256s")
stdin