'How to change function arguments in C?
Inside a C function I am basically trying to convert all the values of the func argument into uppercase. Then use that argument somewhere else in the function. I don't want to change the variable passed into the function. Just the argument locally. Argument is an array of chars.
Here is what I tried:
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]);
}
}
How do I achieve this ?
EDIT: I have included all the necessary header files string and ctype for this to work
Solution 1:[1]
If you do not want to change the argument string, you should make a copy for local use:
- if there is a reasonable maximum length for this string, you can use a local array of
char; - otherwise you can allocate memory for the copy and
- use a loop to convert the contents to upper case
- and free this copy before returning (if it was allocated)
Note that the argument should not be char *word[], but char *word or better const char *word.
Here is an example:
#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] = '\0';
// use copy for the computation
[...]
free(copy);
return res;
}
Solution 2:[2]
If you don't want to change the string passed into your function, make a copy of it and work on that.
void foo(char *bar) {
char *s = strdup(bar);
// do something to s
// bar remains unchanged
// don't forget to free that memory.
free(s);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chqrlie |
| Solution 2 | Chris |
