Emiliano Rodriguez Emiliano Rodriguez - 3 months ago 11
C Question

Filling an array with a string on a side function. Why does it prints gibberish?

I can't find help about this. Most issues i found are related to not closing the array with a '\0' , but this is not the case.

void main() {
char text[1000];
int index=0;
loadText(text,&index);
printf("\nThe text is:\n %s",text);
getch();
}

void loadText(char* text,int* index){
printf("Insert the text: \n");
while((*index<1000) && (text[*index]=getchar())!=EOF) {
*index++;
}
text[*index]='\0';
}


When i print the array it shows random chars.

On a side note, this is a test and we are forced to write the function as:

void loadText(char*, int*)

Answer

In

*index++;

doesn't increment the the value in the pointer. Instead it gets the value ie (*index) and then increment the pointer itself (index=index+1).

Do

(*index)++;