在C函数中从数组返回项
所以,我在做这个刽子手游戏。我在数组和指针方面有点问题。这就是我所拥有的:在C函数中从数组返回项,c,arrays,pointers,C,Arrays,Pointers,所以,我在做这个刽子手游戏。我在数组和指针方面有点问题。这就是我所拥有的: char* getword(int index); int main (void) { char *secword = getword(1); printf("%s ", *secword); } char *getword(int index) { char *words[8]= {'bye', 'hi','what', 'cat', 'dog', 'bird', 'ai
char* getword(int index);
int main (void) {
char *secword = getword(1);
printf("%s ", *secword);
}
char *getword(int index)
{
char *words[8]= {'bye', 'hi','what', 'cat', 'dog',
'bird', 'air', 'water', 'fire'};
return words[index];
}
我一直遇到一个分段错误(核心转储)错误。您有四个重要错误
getword()
函数之外使用words
,因为它是在函数的堆栈框架中分配的
因此,当函数返回时,数组被解除分配,从而发生未定义的行为printf()
要求每个“%s”
说明符都有一个char
指针,*secword
具有类型char
,因此这也是错误的,因为您没有启用编译器警告,它正在重新编译9
字初始化数组,而不是8
,这是编译器警告报告的另一个问题getword()函数中将words
设为静态
const char *getword(int index);
int main (void)
{
char *secword = getword(1);
printf("%s\n", secword);
}
const char *getword(int index)
{
static const char *words[9] = {"bye", "hi", "what", "cat", "dog",
"bird", "air", "water", "fire"
};
return words[index];
}
words
,并将其传递给getword()
char* getword(int index);
int main (void) {
char *secword = getword(1);
printf("%s ", secword);
}
char *getword(int index)
{
static char *words[9]= {"bye", "hi","what", "cat", "dog",
"bird", "air", "water", "fire"};
return words[index];
}
应该是这样的…您的程序有几个问题:
char*
变量(或任何指针)时,必须始终首先使用malloc分配内存。别忘了把它也放出来。手动分配内存的另一种方法是使用固定大小的数组printf(“%s”,*secword)
)C中的字符串使用双引号。该数组中还有9个字符串,而不是8个。是的-您是如何做到segfault的??使用
char const*
而不是char*
,并且您需要使用printf(“%s”,secword))代码>或printf(“%c”,*secword)代码>。注意编译消息;如果出现任何警告或错误,甚至不用麻烦运行程序--首先修复错误…假设返回本地数组指针的尝试没有首先失败,(假设任何东西都编译了).如果要从局部变量向函数返回值,请使用static
限定符,因此在本例中,它应该是static char*words[8]代码>,因为当函数返回其堆栈帧时,其所有局部变量都将被销毁,但是如果你使用static
你会把变量放在段中。data
段istead of stackHave upvote-我想知道什么时候会有人最终建议const。static
是不必要的,而words
在返回后无效,words[index]
是(字符串文字具有静态存储持续时间)。根据我的经验,注意警告比建议请求更多更重要——除了3,编译器已经发出警告(如果不是ANSI之前的编译器,我假设是这样)。
char* getword(int index);
int main (void) {
char *secword = getword(1);
printf("%s ", secword);
}
char *getword(int index)
{
static char *words[9]= {"bye", "hi","what", "cat", "dog",
"bird", "air", "water", "fire"};
return words[index];
}