c - 基本的C编程字符串数组

标签 c arrays string printf character

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*functions
int addHugeNumbers(char *a1,char *a2, char *res);

*/


/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main() {

    /*variables*/
    char str[1001];
    int i;
    /**/

    printf("Give the string that contains the numbers that you want to add.\n");
    printf("The strings must not contain more than 1000 characters.\n");
    scanf(" %s",&str);
    for(i=0;i<1001;i++){
        printf("element is %s",str[i]);
    }
    return 0;
}'

最佳答案

首先,让我告诉你,你的代码中没有字符串数组,它是一个 char 的数组。 s。

说到问题,它是双重的。

首先,打印 char ,您需要使用%c格式说明符,%s适用于字符串(空终止char数组)。

其次,在循环条件下。当你说

for(i=0;i<1001;i++)

索引迭代数组的所有元素。但是,如果您的输入小于 1000 char s,那么数组的某些部分仍然未初始化。访问未初始化的变量值会调用 undefined behavior .

基本上,您应该执行类似的操作,而不是循环遍历整个数组

 int len = strlen(str);
 for(i=0; i<len; i++)
      printf("element is %c",str[i]);

这会将您的索引限制为有效值。

也就是说,scanf()声明应该更好地类似于

scanf("%1000s",str);   //protect from buffer overflow from reallylonginputstring.....

关于c - 基本的C编程字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37422528/

相关文章:

c++ - 联盟内部结构

c - 我是否应该针对 I/O 应用程序的大小 (-Os) 进行优化

c - C中的printf如何对 float 进行舍入?

javascript - 在索引数组javascript中搜索索引值

python - 纠正文本中错别字的最佳算法

javascript - 将类似字符串的数组替换为带有字符替换的数组

c - 使用指针变量分配数组元素值时,第三个数组元素不会打印出来

java - System.arrayCopy 很慢

c - 如何修复此比较字符串(来自 argv 和 scanf)程序?

c++ - 当一个字符串是 ""或一个 vector 没有元素时, `begin()` 等于 `end()` 吗?