-5

Can I run without debugging? The code will not compile because I am trying to convert a char to an int and vice versa. I am just looking for a solution that would allow my char to become an int so on and so forth.

#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;
}
E1y1rac
  • 13
  • 4
  • I'm not sure why all of the comments asking for clarification have been removed. The question is still unclear: what is the actual goal? Code comments say, e.g., `//Iterate through the int array with the int_pointer`, yet this code attempts to step through a `char` array using `int_pointer`. Why? Note that you can't cast your way out of trouble whenever the compiler disagrees with you. In particular, you have UB when attempting to access a `char` array through an `int `pointer. [See this.](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) – ad absurdum Oct 17 '18 at 14:29
  • @DavidBowling are you running in GCC I'm using VS2015. Not sure if that makes a difference. I am fairly new at this and am teaching myself from a book I purchased. So I'm still trying to learn TBH – E1y1rac Oct 17 '18 at 18:47

1 Answers1

0

Turns out I am able to use data typecast for the pointer's data type. I will include the updated code with revisions.

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;
}
E1y1rac
  • 13
  • 4