use*_*514 3 c arrays segmentation-fault
我需要从控制台读取输入并将其放入一个字符数组中.我写了以下代码,但是我收到以下错误:"Segmentation Fault"
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
int count;
char arr[50];
c = getchar();
count = 0;
while(c != EOF){
arr[count] = c;
++count;
}
return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>
#include <stdlib.h>
int main() {
char c; /* 1. */
int count;
char arr[50];
c = getchar(); /* 2. */
count = 0;
while (c != EOF) { /* 3. and 6. and ... */
arr[count] = c; /* 4. */
++count; /* 5. */
}
return (EXIT_SUCCESS); /* 7. */
}
Run Code Online (Sandbox Code Playgroud)
c应该是一个int.getchar()返回一个int来区分有效字符和EOFarr元素中count每次循环都需要读取不同的字符.(3.,4.,5.)
并且您不能在数组中放置比预留的空间更多的字符.(4)
试试这个:
#include <stdio.h>
#include <stdlib.h>
int main() {
int c; /* int */
int count;
char arr[50];
c = getchar();
count = 0;
while ((count < 50) && (c != EOF)) { /* don't go over the array size! */
arr[count] = c;
++count;
c = getchar(); /* get *another* character */
}
return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
编辑
在你拥有数组中的字符后,你会想要对它们做些什么,对吧?因此,在程序结束之前,添加另一个循环来打印它们:
/* while (...) { ... } */
/* arr now has `count` characters, starting at arr[0] and ending at arr[count-1] */
/* let's print them ... */
/* we need a variable to know when we're at the end of the array. */
/* I'll reuse `c` now */
for (c=0; c<count; c++) {
putchar(c);
}
putchar('\n'); /* make sure there's a newline at the end */
return EXIT_SUCCESS; /* return does not need () */
Run Code Online (Sandbox Code Playgroud)
注意我没有使用字符串函数printf().我没有使用它,因为arr不是字符串:它是不(一定)有0(NUL)字符的简单数组.只有带有NUL的字符数组才是字符串.
要将NUL放入arr,而不是将循环限制为50个字符,将其限制为49(为NUL节省一个空格)并在结尾添加NUL.循环后,添加
arr[count] = 0;
Run Code Online (Sandbox Code Playgroud)
#include <stdio.h>
#include <stdlib.h>
int main() {
int c;
int count;
int arr[50];
c = getchar();
count = 0;
while( c != EOF && count < 50 ){
arr[count++] = c;
c = getchar();
}
return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)
请注意while循环中的&& count <50.如果没有这个,你可以超越arr缓冲区.
| 归档时间: |
|
| 查看次数: |
63643 次 |
| 最近记录: |