Question:
What is wrong with this C code?
?
2015-05-21 13:19:50 UTC
/////////////////////////////////////////////C-Code goes like this////////////////////////////
char c;
char temp_arr[20];
i = 0;

c = 'L' ;
temp_arr[ i++ ] = c;
//////////////////////////////////////////////////////////////////////////////////////////////////////////

----------------------------------------------------------
>>Program crashes on running exe file.
>>I m using Visual C++.
----------------------------------------------------------
Four answers:
llaffer
2015-05-21 13:35:35 UTC
well, everything you have here is legal and legit.



What didn't you tell us. I have a feeling it has something to do with that loop and the "i" variable, and you're reaching past the boundary of the character array.
John
2015-05-21 13:53:25 UTC
You ran out of bounds. You have allocated for 20 characters, but i++ (which must be int) quickly goes past).

/* file: crap.c */

#include

int main(void) {

&bsp; char c;

&bsp; char temp_arr[20];

&bsp; int i = 0;

&bsp; char c = 'L';



&bsp; for (i ; i < 19 ; )

&bsp; temp_arr[i++] = c;



&bsp; printf("%s\n", temp_arr);

return 0;

}

/* output:

:~/c$ ./crap

LLLLLLLLLLLLLLLLLLL

*/

>

> John (gnujohn@gmail.com)
aletheia
2015-05-21 13:20:59 UTC
i dont know
?
2015-05-21 13:32:54 UTC
You can't write to an array like that. You have to do it inside of a "for" loop.



for (i = 0; i < 20; i++) {

temp_arr[i] = "L";

end;





Or you can do it this way:



char temp_arr[20] = { "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L" };







Your problem is in this line:

c = 'L' ;


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...