学习C并有很多疑问。
我有一个调用另一个函数的函数(比如函数1)(比如函数2)。 函数2计算字符串数组。
如何在函数1中使用此数组?
一些代码示例:
int find_errors(char* word)
{
char error[100];
/*Given the word, It will find the duplicate chars and store it in the
error array. */
return 0;
}
int find_word(char* word)
{
find_errors (word);
printf("%s\n", error);
return 0;
}
答案 0 :(得分:5)
至少有三种可能的方法:
答案 1 :(得分:2)
有多种方法可以做到这一点。
1)创建一个动态数组并返回一个指向该数组的指针。这将要求您稍后手动释放阵列的内存。
#define NUM_ELEMS 50
// In find_error():
char* error = malloc(NUM_ELEMS * sizeof(char));
return error;
// In find_word():
char *error = find_errors();
// do stuff
free(error);
2)将指针传递给find_errors,它可以用作错误数组。这不需要您手动释放内存。
// In find_word():
char error[NUM_ELEMS];
find_error(error);
3)使用全局数组。可能会让其他人更难理解您的代码。还有其他潜在的问题。
// In global scope:
char error[NUM_ELEMS];
答案 2 :(得分:0)
您需要全局声明error
数组,并像使用它一样使用它。
编辑:在大多数情况下,使用全局变量并不是最好的做法,就像这一样。
答案 3 :(得分:0)
您的问题与“按引用调用”和“按值调用”有关。
char* getNewValsToSet(void)
{
char* new_vals = (char*) malloc(sizeof(char[5]));
new_vals[4] = '\0';
return new_vals;
}
void setValuesEven(char* vals_to_set)
{
vals_to_set[0] = 'A';
vals_to_set[2] = 'C';
}
void setValuesOdd(char* vals_to_set)
{
vals_to_set[1] = 'B';
vals_to_set[3] = 'D';
}
int main(void)
{
char* some_vals_to_set = getNewValsToSet();
setValsEven(some_vals_to_set);
setValsOdd(some_vals_to_set);
// ... now has vals "ABCD"
free(some_vals_to_set); //cleanup
return 0;
}
如果你对学习C有“怀疑”,恕我直言,这是你可以做的最好的事情之一(无论你工作的语言是什么),因为它会解释 事情是如何工作的“ -the-hood“(所有高级语言都试图在某种程度上隐藏)。
答案 4 :(得分:0)
以下是使用精彩控制台输出查找内容的示例。它动态分配数组以保存可能发生的任何数字错误(在您的情况下为重复字符)。
//Only free errors if result is > 0
int find_errors(char* word, char** errors)
{
int num_errors = 0;
int word_length = strlen(word);
int ARRAY_SIZE = MIN(8, word_length);
char existing[word_length];
int existing_index = 0;
*errors = NULL;
for(int i = 0; i < word_length; i++)
{
char character = word[i];
//Search array
for (int n = 0; n < word_length; ++n ) {
if(n >= existing_index)
{
existing[n] = character;
existing_index++;
break;
}
if (existing[n] == character) {
num_errors++;
if(!*errors)
*errors = (char*)malloc(ARRAY_SIZE * sizeof(char));
//Check if we need to resize array
if(num_errors >= ARRAY_SIZE)
{
ARRAY_SIZE *= 2;
ARRAY_SIZE = MIN(ARRAY_SIZE, word_length);
char *tmp = (char*)malloc(ARRAY_SIZE * sizeof(char));
memcpy(tmp, *errors, (unsigned long)ARRAY_SIZE);
free(*errors);
*errors = tmp;
}
//Set the error character
(*errors)[num_errors - 1] = character;
break;
}
}
}
return num_errors;
}
int find_word(char* word)
{
char* errors;
int errCount = find_errors (word, &errors);
if(errCount > 0)
{
printf("Invalid Characters: ");
for(int i =0; i < errCount; i++)
{
printf("%c ", errors[i]);
}
printf("\n");
free(errors);
}
return 0;
}
int main(int argc, char *argv[])
{
find_word("YWPEIT");
find_word("Hello World");
find_word("XxxxXXxXXoooooooOOOOOOOOOOOOOOOooooooooOOOOOOOOOOOOooooooOOO");
}