I have one of the those "assignment makes integer from pointer without a cast" question. I thought I casted the malloc correctly but it still seems to give me a warning.
I recently started C and starting to go deeper into pointers and mallocs.
the program is suppose to prompt for an integer (for how long the string is) then ask again for how many spaces before the prompted text) prompts for text)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_LINE 256
int enterIntegerInRange (int min, int max)
{
char line[MAX_LINE];
do{
printf("Please enter an integer between 0-255: ");
fgets(line,MAX_LINE,stdin);
}
while ((0 < min) || (255>max));
}
void enterText (char* text, int length)
{
printf("Please Enter some text: ");
fgets(text,length,stdin);
}
char* createField (int fieldWidth, int numTabs,const char* text)
{
int lengthText = strlen(text);
char* toP = (char*)malloc(fieldWidth + 1);
int i;
for (i = 0; i < numTabs; i++){
toP[i] = " ";}
int j;
for (j = 0; j < lengthText; j++){
toP[numTabs + j] = text[j];}
toP[i]='\0';
return(toP);
}
int main ()
{
char text[MAX_LINE];
int fieldWidth;
int numTabs;
char* fieldPtr;
while (1)
{
fieldWidth = enterIntegerInRange(0,MAX_LINE-1);
if (fieldWidth == 0)
break;
numTabs = enterIntegerInRange(1,fieldWidth-1);
enterText(text,MAX_LINE);
fieldPtr = createField(fieldWidth,numTabs,text);
printf("\"%s\"\n",fieldPtr);
free(fieldPtr);
}
return(EXIT_SUCCESS);
}
The problem is specifically is in the createField function:
toP[i] = " ";
I thought the taking in consideration for null would work.
Could you tell me what assignment makes an integer and how to go about fixing this?