2015-03-08 101 views
-1

所以,我正在研究这个hang子手游戏。我在数组和指针方面有点麻烦。这是我有:在C函数中返回一个数组中的项目

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]; 
} 

我不断收到一个分段错误(核心转储)错误。

+4

C中的字符串使用双引号。该阵列中还有9个字符串,而不是8个。 – 2015-03-08 21:05:03

+1

是的 - 你是如何设法达到段错误的? – 2015-03-08 21:06:28

+1

使用'char const *'而不是'char *',并且您需要使用'printf(“%s”,secword);'或'printf(“%c”,* secword);'。并注意编译器消息;如果有任何警告或错误,甚至不打扰你的程序运行 - 首先解决错误。 – 2015-03-08 21:06:59

回答

1

你有四个重要的错误

  1. 不能使用getword()功能words外面是因为它在函数的栈帧的已分配。

    所以当函数返回时,数组被解除分配,从而发生未定义的行为。

  2. 您的阵列中不包含字符串,而是多字符包含而不是。 多字符常量是有效的,但是已经定义了实现,所以不能依赖它们来实现便携式程序。

    因为您未启用警告,所以您的代码编译,然后当您尝试访问这些打印值的地址时,将依赖于多字符常量实现的整数值分配给数组的poitners他们然后发生未定义的行为。

  3. printf()需要一个char指针每个"%s"符,*secword具有类型char所以这也是错误的,它再次编译,因为你没有启用编译器警告。

  4. 您正在用9字初始化数组,而不是8,这是编译器警告会报告的另一个问题。

您有2个选项

  1. words静在getword()功能

    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]; 
    } 
    
  2. 声明words主,并将其传递给getword()

    const char *getword(int index, const char *words[]); 
    int main (void) 
    { 
        const char *words[9] = {"bye", "hi", "what", "cat", "dog", 
              "bird", "air", "water", "fire" 
        }; 
        char *secword = getword(1, words); 
        printf("%s\n", secword); 
    } 
    
    const char *getword(int index, const char *words[]) 
    { 
        return words[index]; 
    } 
    

我一直在写c程序一段时间,并且我使用尽可能多的警告,如果我是一个新的程序员学习c,我会尽可能地启用更多的警告。

+0

有一个upvote - 我想知道什么时候有人最终会建议const。 – 2015-03-09 05:30:28

+0

'static'是不必要的,而'words'在返回后无效,'words [index]'是(字符串文字具有静态存储持续时间)。根据我的经验,注意警告是比建议请求更多的更重要的部分 - 除了3,编译器已经警告过(如果它不是ANSI之前的编译器,我认为)。 – mafso 2015-03-09 08:52:31

0
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]; 
} 

应该是这样的......

0

有几件事情是不对您的程序:

  1. 当使用char*变量(或任何指针),你必须始终分配他们首先用malloc记忆它们。不要忘记释放它。手动分配内存的替代方法是使用固定大小的数组。

  2. 打印时不要对字符串取消引用(printf("%s ", *secword))。

  3. 确保在声明数组时指定正确数量的元素(有9个,而不是8个),并且不要忘记检查是否跨越数组边界。

  4. 在C中,所有的字符串都是双引号;单引号表示字符常量。