C语言static问题
为什么加上static的变量在主函数中才能返回,不加static返回的就是空?
#include<string.h>
char* longestCommonPrefix(const char** strs, int strsSize) {
char string[200];//用来存放返回结果
int k = 0; //用来定义数组下标
for (int i = 0; i < strsSize; i++) //用来循环当前是第几个字符串
{
for (int j = 0; j <= strlen(strs[i]); j++) {//用来进行列的比较
if (i == 0) {
string[k] = strs[i][j];
k++;
continue;
}
else if (string[j] == strs[i][j]) {
continue;
}
else {
string[j] = '\0';
}
}
}
printf("%s\n", string);
return string;
}
int main() {
//定义一个字符串数组
const char* strs[] = { "flower", "flow", "flight" };
//计算数组长度
int size = sizeof(strs) / sizeof(strs[0]);
//调用函数并打印结果
char* string;
string = longestCommonPrefix(strs, size);
printf("The longest common prefix is: %s\n", string);
return 0;
}
#include<string.h>
char* longestCommonPrefix(const char** strs, int strsSize) {
static char string[200];//用来存放返回结果
int k = 0; //用来定义数组下标
for (int i = 0; i < strsSize; i++) //用来循环当前是第几个字符串
{
for (int j = 0; j <= strlen(strs[i]); j++) {//用来进行列的比较
if (i == 0) {
string[k] = strs[i][j];
k++;
continue;
}
else if (string[j] == strs[i][j]) {
continue;
}
else {
string[j] = '\0';
}
}
}
printf("%s\n", string);
return string;
}
int main() {
//定义一个字符串数组
const char* strs[] = { "flower", "flow", "flight" };
//计算数组长度
int size = sizeof(strs) / sizeof(strs[0]);
//调用函数并打印结果
char* string;
string = longestCommonPrefix(strs, size);
printf("The longest common prefix is: %s\n", string);
return 0;
}