#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/