"Help with C question" is a useless title. Obviously you want help with a C question since you posted a question in a C forum. A better title would be "Writing my own atoi function".
Code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 40
void myItoa(int num, char* str[], int size);
// main returns int, not void
void main() {
int num1;
char* num2 = NULL;
printf("Please enter a number: ");
scanf("%d", &num1);
myItoa(num1, &num2, SIZE);
puts(num2);
free(num2);
}
// What's the point of size? You don't use it.
void myItoa(int num, char* str[], int size) {
int counter = 0;
int tmp = num;
do {
tmp /= 10;
counter++;
} while (tmp);
// str needs to be *str
str = (char*)malloc(counter+1);
// str needs to be *str
if (str == NULL) {
printf("\nAllocation failed.");
return 0; // Your function has void return type (just say return)
}
// This algorithm is totally wrong.
// Also, if you want to add '0' say '0', not 48.
// Instead of *(str+i) you need to say *(*str + i), or (*str)[i]
for (int i = 1, j = 10; i <= counter; i++) {
if (counter - i == 0) {
*(str + i) = (num / j) + 48;
}
// Presumably this should be an 'else' part of the 'if'
*(str + i) = (num / (j * (counter - i)) + 48);
}
// You never '\0' terminate the string
}
Maybe it could be something like this:
Code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myItoa(int num, char** str);
int main() {
printf("Enter a number: ");
int n;
scanf("%d", &n);
char *s = NULL;
myItoa(n, &s);
if (s) {
puts(s);
free(s);
}
return 0;
}
void myItoa(int num, char** str) {
int size = 0;
int tmp = num;
do {
tmp /= 10;
++size;
} while (tmp);
*str = malloc(size + 1);
if (*str == NULL) {
printf("Allocation failed.\n");
return;
}
for (int i = size; i > 0; --i) {
(*str)[i - 1] = num % 10 + '0';
num /= 10;
}
(*str)[size] = '\0';
}
However, this does not handle negative integers. And it would probably be better to return a char* instead of taking a char**.