You can't use the pointer to a local array outside the scope where that array was defined because it's stored in the stack frame of the function and will be popped out when the function finishes and returns, so it will no longer be valid to use it (read it). Instead, you could pass the array from the caller function.
// In the caller function
char data[64];
intToAscii(1234, data);
And the intToAscii() function, simply
void intToAscii(unsigned long x, char *str)
{
int i;
unsigned long n;
for (i = 0; i < 63; i++) {
n = x >> 63;
if (n == 0) {
str[i] = '0';
} else {
str[i] = '1';
}
x = x << 1;
}
str[i] = '\0';
printf("Value of x is %s \n", str);
}
Another mistake, is that you are accessing index 64 of str, but arrays are 0-indexed so 64 is out of bounds besides, the '\0' terminator must be the character right after the last, you can achieve that by using the index i which will have the correct value at the end of the loop and this way it doesn't matter if it's 63 or 64, it's the right value as long as the loop is ending before the last element of the array.
One more thing, functions like this are very dangerous, instead you can pass another parameter to tell the function how many bytes are available in the destination array like this,
void intToAscii(unsigned long x, char *str, size_t size)
{
int i;
unsigned long n;
for (i = 0; i < size - 1; i++) {
n = x >> 63;
if (n == 0) {
str[i] = '0';
} else {
str[i] = '1';
}
x = x << 1;
}
str[i] = '\0';
printf("Value of x is %s \n", str);
}
And finally, as was commented by @David C. Rankin your function returns char but it's body does not return anywhere, that will cause undefined behavior. You don't need your function to return anything because it modifies the array in place.
unsigned longmay only be 32-bit. Better to userunsigned long longoruint46_t, etc.char str[64]; ... str[64]='\0';is a problem.uint64_t:)