Reputation: 613
I have a function that receives an int
and returns a pointer to a string array:
char* DoSomething (int num);
But I don't understand how to deal with it in the main. Essentially I want to print the string I am getting from the function. But in the main I get a warning: assignment from incompatible pointer type. This is my main:
int main()
{
int num = 12345;
char* a;
a = DoSomething(12345);
return 0;
}
Updating. I didn't want to put a long code, but adding as per your request. The function is defined in a separate c file.
/* conver int to String */
char* IntToString (int num)
{
int i;
int sign = 1;
int len;
int begin = 0;
char* str = malloc (sizeof(char)*30);
if (num<0)
{
sign = -1;
num = num*(-1);
}
len = CountDigits(num);
if (sign == -1)
{
str[0]='-';
begin = 1;
}
int newLen = len;
for (i=0; i<len; i++)
{
int digit;
char digitChar;
int modul;
digit = num/(pow(10, newLen-1));
digitChar = digit + ASCII_ZERO;
str[i+begin] = digitChar;
modul = pow(10, newLen-1);
num = num % modul;
newLen--;
}
return str;
}
Then in the main I am trying to call the function:
int main()
{
int num = 12345;
char* a;
a = IntToString(12345);
return 0;
}
Upvotes: 0
Views: 293
Reputation: 726499
You get a warning because the function is defined after main
, and lacks prototype.
Move the function to before main
, or add this line:
char* DoSomething (int num);
Now the warning will be gone, and you would be able to print your string in a way that you prefer, for example
printf("%s\n", a);
Note 1: The string you are returning is not null terminated.
Note 2: Since you are using malloc
in the function, you need to call free
on the result in the main
.
Upvotes: 4