【问题标题】:Is it possible to run this code although I'm trying to change data types?尽管我正在尝试更改数据类型,是否可以运行此代码?
【发布时间】:2018-10-16 14:28:11
【问题描述】:

我可以在不调试的情况下运行吗?代码将无法编译,因为我试图将 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;
}

【问题讨论】:

  • 我不确定为什么所有要求澄清的 cmets 都被删除了。问题仍然不清楚:实际目标是什么?代码 cmets 说,例如 //Iterate through the int array with the int_pointer,但此代码尝试使用 int_pointer 单步执行 char 数组。为什么?请注意,只要编译器不同意您的意见,您就无法摆脱困境。特别是,当您尝试通过int pointer 访问char 数组时,您有UB。 See this.
  • @DavidBowling 你在 GCC 中运行吗?我使用的是 VS2015。不确定这是否会有所作为。我对此很陌生,并且正在从我购买的一本书中自学。所以我还在努力学习TBH

标签: c pointers


【解决方案1】:

原来我可以对指针的数据类型使用数据类型转换。我将在修订中包含更新的代码。

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;
}

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2019-01-26
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多