Convert an int pointer to a char pointer when the int values are guaranteed to be less than 256 in C

c type conversion rules
pointers in c
size of character pointer in c
size of int pointer in c
implicit type conversion in c example
usual arithmetic conversions
c integer promotion
c integer conversion rules

I have an int*:

int arr[4];
int *x = arr;
x[0] = 65;
x[1] = 66;
x[2] = 67;
x[3] = 0; // terminating null

Then I want to print these values as characters:

char *y = magical_function(x);
printf(y);

The output should be ABC. How do I get or define this magical function?

Note: If I happened to have this: x[2] = 1000;, then I honestly don't care what the answer does. It may ignore the higher bits, error, whatever, it's UB in this case.

This doesn't work:

char *y = (char*) x;

...since the output is just A, probably since the char* interprets the int as 4 chars and the 2nd of those chars is a null byte, which ends the string:

int arr[4];
int *x = arr;
// x points to the following memory:

 x->01000000 (x[0])
    00000000
    00000000
    00000000 (65)
    -------- (x[1])
    01000001
    00000000
    00000000
    00000000 (66)
// if casted to a char*:

y->01000000 "A"
   00000000 "\0"
   00000000 "\0"
   00000000 "\0" etc.

int and char probably have different sizes, so you can't just cast the pointers, as they would be read/written incorrectly. If you have an array of integers and you need an array of some other type, be that char, float, or just a differently sized integer, you need to make a new array and convert each item.

/*magical_function*/
/*Assuming arr is "null terminated". Don't forget to call free().*/
char *int_to_char_array(int *arr)
{
    size_t len = 0;
    int *p = arr;
    do {
        ++len;
    }  while (*p++);
    char *out = malloc(len); // Allocate space needed for same number of chars
    for (size_t i = 0; i < len; ++i)
        out[i] = (char)arr[i]; // convert each element
    return out;
}
int main() {
    // As in OP
    int arr[4];
    int *x = arr;
    x[0] = 65;
    x[1] = 66;
    x[2] = 67;
    x[3] = 0; // terminating null

    char *str = int_to_char_array(arr);
    printf("%s\n", str); // or any normal string function
    printf("length %i\n", strlen(str));
    free(str);
}

Runnable demo: http://tpcg.io/fPETPE

C Basics - C Programming Tutorial, Below is a simple C program that illustrates the important programming It is called variable because you can change the value stored. Integers: C supports these integer types: char , short , int , long , long long (in If the value to be formatted is shorter than the field width, it will be padded 11.2 String as char pointer. Compliant Solution. Any valid pointer to void can be converted to intptr_t or uintptr_t and back with no change in value. (See INT36-EX2.).) The C Standard guarantees that a pointer to void may be converted to or from a pointer to any object type and back again and that the result must compare equal to the original pointer.

In that case I would just change the format specifier to %c

e.g.:

int a = 65;
printf("%c\n", a);

Implicit conversions, undergoes a conversion to the non-lvalue pointer to the function designated by the expression. int f(int); int (*p)� All a "char" is in C is an integer with enough bytes to represent every ASCII character. If you want to convert an int to a char, you'll need to instruct the computer to interpret the bytes of an int as ASCII values - and it's been a while since I've done C, but I believe the compiler will complain since char holds fewer bytes than int. This

I want to print these values as characters...The output should be ABC. How do I get or define this magical function?

It's called printf and it's definition located in stdio.h. See more here: http://www.cplusplus.com/reference/cstdio/printf/

#include <stdio.h>

int main()
{

    int arr[4] = {65, 66, 67, 0};

    for(int i = 0; i < 4; i++) printf("%c", arr[i]);

    return 0;

}

Tested code here: http://tpcg.io/AFwhXt

4. Type Conversions - C in a Nutshell [Book], For example, a pointer to a structure can be converted into a different pointer type . use a value whose type ranks lower than int in place of an operand of type int or char c = '?'; unsigned short var = 100; if ( c < 'A' ) // The character constant 'A' converting the pointer value back into the original pointer type is guaranteed� Similarly, reinterpret_cast can be used to convert an integer type into a pointer type. Again the result is implementation-defined, but a pointer value is guaranteed to be unchanged by a round trip through an integer type. The standard does not guarantee that the value zero is converted to a null pointer.

The following code is based on the basis of being 0 of the last element in the input.

#include <stdio.h>
#include <stdlib.h>

char *
magical_function (int const *x) {
    size_t numOfElements = 0;
    size_t i = 0;
    for (i = 0; x[i] != 0 ; ++i, ++numOfElements) ;
    char *p = malloc(numOfElements + 1);
    if (!p) {
        perror("malloc error");
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < numOfElements; ++i) {
        p[i] = (char)x[i];
    }
    p[i] = 0;
    return p;
}

int
main (void) {
    int arr[4];
    int * const x = arr;

    x[0] = 65;
    x[1] = 66;
    x[2] = 67;
    x[3] = 0;

    char *y = magical_function(x);
    puts(y);
    free(y);

    return 0;
}

Coding resources, Pointers in C are a critical concept when you program in C. A pointer is a memory address. potential value range of 0-255 (2 values/bit ^ 8 bits = 256 possible values). cat main.c #include <stdio.h> int main(void) { printf("The size of a pointer is sizeof(char *)); printf("The size of a char pointer is %ld bytes!\n", sizeof(int *))� Strictly speaking, you can do this: (int)pointer. However, you are probably looking for the atoi and atof functions. atoi is a function that converts a char* pointing to a string containing an integer in decimal to an integer. atof is likewise for double.

Type Conversion Vulnerabilities, In this case, all values less than 0 have their value changed to a high positive number when char *indx; int count; char nameStr[MAX_LEN]; //256 to be gone because the character pointer, indx, is now an unsigned type. int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address.

C data types, In the C programming language, data types constitute the semantics and characteristics of The C language provides the four basic arithmetic type specifiers char, int, float the value 256 does not fit in the data type, which results in the lower 8 bits of it Pointer integer types that are guaranteed to be able to hold a pointer. @HaSeeBMiR The only reason the answer is related to C instead of C++ is that it uses a C header instead of the equivalent C++ header. The C preprocessor is a part of C++, and cstdint is a part of the C++ standard, as are all of the type names defined there.

C Programming Tutorial, This is a C Programming Tutorial for people who have a little experience with an functions visibly in a program */ main () { int i; /* declarations */ do { /* Nothing !!! is an ASCII code given in octal or base 8, See Character Conversion Table. these are detailed in the section on pointers) such as finding out the value of i� C and C++ define character types (char, unsigned char and signed char) to have a size of one byte, and require them to have at least 8 bits. There is, or at least until recently was a machine with 9 bit char , and there are some with 32 bit char. (Historically, of course, there were a lot of machines with bytes less than 8 bits, but C doesn't allow this.)

Comments
  • @EugeneSh. It's just an array actually. int arr[]; int *x = arr;
  • Since there is no magic, you will have to perform the conversion element-wise.
  • to have a char pointing to the byte with the value < 0x100 you need to take into consideration the endianess
  • tpcg.io/fPETPE if the OP has an array as specified, will create a null terminated string from it.
  • @P__J__ Well, its impossible to just cast a 4 element int pointer into a 4 element char pointer and get the same numbers. If he want's literally the same pointer, then maybe can do it in-place.
  • The cast you proposed makes the conversion: char * y = (char *) x. The problem is at your printf. If the format specifier is for integers it will cast y to an integer. That's why it prints the ASCII value of y.
  • Just printf("%c\n", x[0]) and see what happens.
  • I want to print the entire string, not just a character. What if I want y[1]? It would give me part of the x[0] integer, since an integer is 4 bytes wide.
  • Ok, now I see what you mean. You can't make that kind of cast since the memory allocated to the int array will use 4 bytes. It can't know that you want only the first byte of each position. The y array would have to point to segmented blocks of memory. The only way I know you could do that is with a loop iterating the int array and printing each element as a char.
  • Suggest i < 4 --> arr[i] != 0
  • But I don't want to print the chars. I want to put them in a char array/pointer.