【发布时间】:2014-12-06 20:58:04
【问题描述】:
我在准备考试时尝试完成的问题如下:
:考虑一个具有此原型的函数: 无效转换(字符列表 [],字符 ch 1,字符 ch2); "convert" 函数将它在 "list" 中找到的每个字符 chi 更改为 字符 ch2。例如,函数调用“convert (name,'a','z')”将转换每个 'a' 到 'z' 在名为“name”的数组中。写出函数“convert”的定义。
我的程序运行到 main 中的两个 scanf 函数结束,我正在研究如何在不使用指针的情况下传递参数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char list[];
char ch1;
char ch2;
void convert(char list[], char ch1, char ch2);
int main()
{
char list[15];
char ch1, ch2;
printf("Enter a string of characters:");
scanf("%s", list);
printf("Enter the first letter:");
scanf("%c\n", &ch1);
printf("Enter the second letter:");
scanf("%c\n", &ch2);
}
void convert(char list[], char ch1, char ch2)
{
int wordcount;
int i = 0;
int x = 0;
int y = 0;
if (list[i] == ch1)
{
x++;
list[i] = ch2;
}
else if (list[i] != ch1)
{
y++;
}
else if (list[i] == NULL)
{
wordcount = (y + x + 1);
}
printf("In the string there are %d letters and in %s the letter %c was changed to %c, %d times.", wordcount , list, ch1, ch2, x);
}
【问题讨论】:
-
在 main 处致电
convert(list, ch1, ch2);。但是 convert (char list[]) 的第一个参数是指针,而不是数组。 -
当数组传递给函数时,按值传递(指针的)。如果您可以更改原型,则通过结构传递值(包括数组)包装数组。
-
谢谢,我认为声明全局变量背后的想法是使各种函数能够使用该变量。另外我只是想澄清一下,指针位于写入字符串的 main 的开头?
-
在这种情况下,传递给函数的指针指向 main 的字符串。
-
好的,感谢您的澄清。
标签: c parameter-passing