我知道字符串只是一个具有相邻内存地址的字符数组。所以当你有一个字符数组时:
char s[5];
s[0] = '1';
s[1] = '2';
s[2] = '3';
s[3] = '4';
s[4] = '5';
并将 s[1] 处的字符数组更改为“5”,然后打印这样的数组应返回“15345”。现在我的问题是关于 scanf 和 strtol 函数。当我使用 scanf 两次使用不同大小的字符串将值插入数组 s 时,为什么 strtol 函数不转换整个数组?
这是我的代码作为示例:
#include <stdio.h>
#include <stdlib.h>
int main(){
char bytes[5];
printf("enter size 1: ");
scanf("%s", bytes);
printf("the size is: %ld\n", strtol(bytes, NULL, 10));
printf("enter size 2: ");
scanf("%s", bytes);
printf("the size is: %ld\n", strtol(bytes, NULL, 10));
return 0;
}
想象一下这些用户输入:
10000
然后程序将打印出“大小为 10000”
然后用户输入:
100
然后程序打印“大小为 100”
为什么它不再打印出“大小为1000”?我只将 100 存储为字节,第一个输入中字节的剩余数组元素不应该保持不变, strtol 应该转换数组的其余部分吗?
在我看来,当程序将第一个输入 10000 存储到数组字节中时,那一刻看起来像这样
字节 = {1,0,0,0,0}
然后当用户输入 100 时,数组看起来是一样的,因为它只改变了前 3 个元素的值,而数组的其余部分应该保持不变:
字节 = {1,0,0,0,0}
使用该 strtol 会将整个数组转换为 10000 对吗?
将值存储到同一内存地址时,scanf 是否本质上“清空”了数组的其余部分?