如何更改 C 中的函数参数?
How to change function arguments in C?
在 C 函数中,我主要是尝试将 func 参数的所有值都转换为大写。然后在函数的其他地方使用那个 argument。我不想更改传递给函数的变量。只是当地的争论。参数是一个字符数组。
这是我尝试过的:
int calculate_score(char *word[])
{
for (int i = 0, n = strlen(word); i < n; i++)
{
if (islower(word[i]) != 0)
{
//this piece of code is not working
toupper(word[i]);
}
}
我该如何实现?
编辑:我已经包含了所有必要的头文件字符串和 ctype 以使其工作
如果您不想更改传递给函数的字符串,请制作一个它的副本并进行处理。
void foo(char *bar) {
char *s = strdup(bar);
// do something to s
// bar remains unchanged
// don't forget to free that memory.
free(s);
}
如果您不想更改参数字符串,您应该复制一份供本地使用:
- 如果这个字符串有合理的最大长度,你可以使用
char
的本地数组;
- 否则你可以为副本分配内存并且
- 使用循环将内容转换为大写
- 并在返回前释放此副本(如果已分配)
请注意,参数不应该是 char *word[]
,而是 char *word
或更好的 const char *word
。
这是一个例子:
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int calculate_score(const char *word) {
int res = 0;
size_t i, n = strlen(word);
char *copy = malloc(n + 1);
if (copy == NULL) {
fprintf(stderr, "calculate_score: allocation error\n");
return -1;
}
for (i = 0; i < n; i++) {
unsigned char c = word[i];
copy[i] = (char)toupper(c);
}
copy[i] = '[=10=]';
// use copy for the computation
[...]
free(copy);
return res;
}
在 C 函数中,我主要是尝试将 func 参数的所有值都转换为大写。然后在函数的其他地方使用那个 argument。我不想更改传递给函数的变量。只是当地的争论。参数是一个字符数组。
这是我尝试过的:
int calculate_score(char *word[])
{
for (int i = 0, n = strlen(word); i < n; i++)
{
if (islower(word[i]) != 0)
{
//this piece of code is not working
toupper(word[i]);
}
}
我该如何实现?
编辑:我已经包含了所有必要的头文件字符串和 ctype 以使其工作
如果您不想更改传递给函数的字符串,请制作一个它的副本并进行处理。
void foo(char *bar) {
char *s = strdup(bar);
// do something to s
// bar remains unchanged
// don't forget to free that memory.
free(s);
}
如果您不想更改参数字符串,您应该复制一份供本地使用:
- 如果这个字符串有合理的最大长度,你可以使用
char
的本地数组; - 否则你可以为副本分配内存并且
- 使用循环将内容转换为大写
- 并在返回前释放此副本(如果已分配)
请注意,参数不应该是 char *word[]
,而是 char *word
或更好的 const char *word
。
这是一个例子:
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int calculate_score(const char *word) {
int res = 0;
size_t i, n = strlen(word);
char *copy = malloc(n + 1);
if (copy == NULL) {
fprintf(stderr, "calculate_score: allocation error\n");
return -1;
}
for (i = 0; i < n; i++) {
unsigned char c = word[i];
copy[i] = (char)toupper(c);
}
copy[i] = '[=10=]';
// use copy for the computation
[...]
free(copy);
return res;
}