c - Difference in printing out pointer value vs array
问题描述
I have a question on printing out pointer value and array.
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
for (int i = 0; i < 5; i++) {
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));
}
Above is what I typed in first but it didn't work. So I erased the printf line and entered a new code which is this. And it worked.
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
I understand why the second one worked but still don't understand why first one didn't.
Expected output was 3 4 5 6 7 but the actual output of the first code was 2 3 4 5 -858993460
解决方案
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
for (int i = 0; i < 5; i++) {
(*ptr) += 2;
ptr++;
printf("%d", (*ptr));
}
The reason is you are incrementing the pointer first and then printing its content.
Perhaps you need to print the contents first then increment it to point next element.
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
for (int i = 0; i < 5; i++) {
(*ptr) += 2;
printf("%d", (*ptr));
ptr++;
}
推荐阅读
- recaptcha - 谷歌建议的 recaptcha.net 在中国也不起作用
- javascript - 将 antd tree-select 下拉框渲染到左侧
- spring - 配置两个端口进行springboot集成测试
- visual-studio-code - VSCode 集成终端(fish)的 pwd 命令总是返回“/”
- macos - 是否可以仅使用 Xamarin Studio for MAC 开发 Xamarin Forms 应用程序?
- go - 如何使用 golang 提供角度服务?
- r - 从矩阵创建新列
- android - 主题订阅在新令牌上无效
- php - 将 select2_from_ajax 与 JSON 数据源一起使用
- kubernetes - Kubernetes 服务中的故障转移机制是如何工作的?