c中使用char数组的总线错误

时间:2017-02-09 03:57:45

标签: c compiler-errors char

我正在尝试自学C语言。到目前为止,我从C的过渡一直很艰难。我正在从“C语言简介”一书中解决问题,并且存在一个问题,即应从用户读取一行,然后向用户询问int。我的工作是找到对应于int 的特定单词。

示例

  

Hello World,你好。 //这是正在读取的行

     

2 //要打印到控制台的单词

预期输出

  

世界

下面是我的代码片段,我认为它给了我总线错误。

input, select { width:100%; padding:14px; margin:10px 0; border:2px solid #6aa295; }

这就是我在void corrspndToInt (char *theLine, int word, char *result ) { int start; int end; int spaces = 1; result = ""; //int i; //search for the nth non-blank character for(start = 0; start < strlen(theLine) && (spaces < word); start++ ) { if( isspace ( theLine[ start ] ) ) { spaces++; } // end if } // end for loop //only need to continue if we haven't gone past the end of the string if( start < strlen(theLine) ) { //the next blank character is the end for ( end = start; end < strlen(theLine) && ( !isspace ( theLine[ end ] ) ) ; end++ ) { ; } // end for loop //we now have the word result = strncpy ( result, theLine+start, end - start); } // end if } 函数中打印结果的方法。

main

现在我一直在给自己教C语言,并且通过SO我学会了返回的char数组不应该完成。使用函数printf("%s\n", result ); 有两种方法动态分配,还有另一种方法是我在代码中实现的方法。我检查了我的另一种方法,似乎没有任何问题。这里的问题是这个方法,因为它没有得到正确的单词。

我一直在尝试调试我的程序,但显然Mac不接受malloc命令。我已经安装了命令行工具和其他所有工具,但它仍然说

  

未找到命令

任何人都可以在这里指导我正确的方向吗?我过去1小时就一直在思考这个问题。

1 个答案:

答案 0 :(得分:0)

首先,您必须为result分配足够的空间来保留单词,这意味着

result = malloc (sizeof(char) * (length_of_the_word+1));

鉴于您已找到要复制的单词的长度。一个额外的原因是,当您使用\0

时,我们希望在字符串末尾添加终止strncpy字符

从功能中不清楚你是否为结果分配了空间。我希望这可以帮助你完成任务。