c - 尽管我正在尝试更改数据类型,是否可以运行此代码?
问题描述
我可以不调试就运行吗?代码将无法编译,因为我试图将 char 转换为 int,反之亦然。我只是在寻找一种解决方案,可以让我的 char 变成 int 等等。
#include "stdafx.h"
#include <stdio.h>
int main()
{
int i;
char char_array[5] = { 'a', 'b', 'c', 'd', 'e' };
int int_array[5] = { 1, 2, 3, 4, 5 };
char *char_pointer;
int *int_pointer;
char_pointer = int_array; //The char_pointer and int _pointer
int_pointer = char_array; //point to incompatible data types
for (i = 0; i < 5; i++) { //Iterate through the int array with the int_pointer
printf("[integer pointer] points to %p, which contains the char '%c'\n", int_pointer, *int_pointer);
int_pointer = int_pointer + 1;
}
for (i = 0; i < 5; i++) { //Iterate through the char array with the char_pointer
printf("[char pointer] points to %p, which contains the integer %d\n", char_pointer, *char_pointer);
char_pointer = char_pointer + 1;
}
getchar();
return 0;
}
解决方案
事实证明我能够对指针的数据类型使用数据类型转换。我将在修订中包含更新的代码。
int main()
{
int i;
char char_array[5] = { 'a', 'b', 'c', 'd', 'e' };
int int_array[5] = { 1, 2, 3, 4, 5 };
char *char_pointer;
int *int_pointer;
char_pointer = (char *) int_array; //Typecast into the
int_pointer = (int *) char_array; //pointer's data type
for (i = 0; i < 5; i++) { //Iterate through the int array with the int_pointer
printf("[integer pointer] points to %p, which contains the char '%c'\n", int_pointer, *int_pointer);
int_pointer =(int *) ((char *) int_pointer + 1);
}
for (i = 0; i < 5; i++) { //Iterate through the char array with the char_pointer
printf("[char pointer] points to %p, which contains the integer %d\n", char_pointer, *char_pointer);
char_pointer = (char *) ((int *)char_pointer + 1);
}
getchar();
return 0;
}
推荐阅读
- javascript - Mongoose:按对象 id 分组并推入一个数组,按 createdAt 排序,填充所有对象并对其进行分页
- ios - 从 CVPixelBufferRef 构造 CAMetalLayer
- sql - Oracle - 日期格式验证
- beautifulsoup - Python BeautifulSoup 从类中获取文本
- java - 如何在 application.properties 文件中覆盖 Spring Boot Starter 的默认属性?
- c# - 当覆盖率太低(使用 C# 和 dotnet 测试)时,如何使 Jenkins 阶段失败并变红?
- python - 当包的名称以“python”开头时,Azure 机器学习 add_conda_package 将失败
- java - Java - 如何在多种方法中使用 HashMap
- linux - 如何从子文件夹中转储文件列表及其在 Linux 中的完整路径
- visual-studio-2012 - 将 NaN 更改为 0