【问题标题】:Stack : not able to push a couple of characters into array堆栈:无法将几个字符推入数组
【发布时间】:2016-12-03 21:11:01
【问题描述】:

我有一个使用数组实现堆栈的代码,这里是完整的代码:here

这就是为什么我不能推送多个字符的原因,但是 只有一个字符? 但我一直在点击一些变量,使用struct 为她的推送进行初始化 数组形式的一些字符:

struct stackMhs {
char nama[10];
char npm[10];
char telp[10];
int size;
};

struct stackMhs stackMhsbaru;

这是push()函数,其参数将是函数main()中的数据内容:

void push(char nm, char np, char tel) {
if(stackMhsbaru.size != 10) {
stackMhsbaru.nama[stackMhsbaru.size + 1] = nm;
stackMhsbaru.npm[stackMhsbaru.size + 1] = np;
stackMhsbaru.telp[stackMhsbaru.size + 1] = tel;
stackMhsbaru.size++;
}
else {
printf("stack is full!");
}
}

问题是当我使用' 填充数据时,push() 函数中只有一个字符,如push('a','b','c');,编译时没有错误,但是当我使用"push("aa","bb","cc"); 时编译时发生错误:

main.c: In function 'main':
main.c:60:6: warning: passing argument 1 of 'push' makes integer from pointer without a cast [-Wint-conversion] 
 push("aa", "bb", "cc"); 
      ^ 
main.c:23:6: note: expected 'char' but argument is of type 'char *'
void push(char nm, char np, char tel) {
     ^
main.c:60:12: warning: passing argument 2 of 'push' makes integer from pointer without a cast [-Wint-conversion]
push("aa", "bb", "cc");
           ^
main.c:23:6: note: expected 'char' but argument is of type 'char *'
void push(char nm, char np, char tel) {
     ^
main.c:60:18: warning: passing argument 3 of 'push' makes integer from pointer without a cast [-Wint-conversion]
push("aa", "bb", "cc");
                 ^
main.c:23:6: note: expected 'char' but argument is of type 'char *'
void push(char nm, char np, char tel) {
     ^ 

我的问题是:任何解决方案?

【问题讨论】:

  • 你的推送函数需要“char”参数,你必须用char*或字符串数​​据类型替换它
  • size 在哪里初始化?

标签: c arrays stack


【解决方案1】:

在 C 中,'' 内的任何内容都是一个字符(使用 char 声明),"" 内的任何内容都表示一个字符串,该字符串是一个以空结尾的 chars 数组。

您不能将 chars 的数组分配给单个 char 变量,因此您会看到警告。

警告说明:

warning: passing argument 1 of 'push' makes integer from pointer without a cast

为了解释起见,假设编译器在说int 时表示char,那么基本上它是在抱怨你试图将char 数组类型分配给char 而没有明确告诉编译器你想这样做。

正确的做法:

将字符串逐个字符传递给循环内调用的push 函数。

【讨论】:

  • assume that the compiler means char when it says int。无需假设,编译器确实意味着 charinteger 类型。
【解决方案2】:

首先你应该更关心你的代码缩进,这样我们更容易阅读。

现在,对于您的问题:'c'"c" 之间的 C 语言存在巨大差异。第一个只是一个字符,第二个是一个以空字符结尾的字符数组,这是完全不同的。

当您调用 push("aa", "bb", "cc"); 时,您将 3 个字符数组提供给需要 3 个字符的函数,这就是您的代码不起作用的原因。

要绕过这一点,您可以使用字符数组中的所有不同字符多次调用您的函数:

char *str = "foo";
while (*str)
    push(*(str++));

这样,while 将在您的字符串中循环,并调用push() 函数将str 中的所有可用字符。

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 2021-12-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多