尽管我正在尝试更改数据类型,但是可以运行此代码吗?

时间:2018-10-16 14:28:11

标签: c pointers

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

1 个答案:

答案 0 :(得分: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;
}