Why arrays are like this? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 2

Why arrays are like this?

I know c has a weird way of storing strings but this is just too confusing. Just look at the code you will see. https://code.sololearn.com/c5L9xal0z06o/?ref=app

17th Apr 2018, 3:43 AM
Akib
Akib - avatar
6 Réponses
+ 1
There is no out of bounds exception in c. You need to take care of this yourself. Accessing an index which is not in the array is not defined. The problem is that the memory you are accessing isn't actually reserved for your array. If something other then uses this memory location and you access it it can produce a runtime error (the segmentation fault xan mentioned)
17th Apr 2018, 6:57 AM
Alex
Alex - avatar
+ 2
When you pass an character array as a parameter to a function, it will be automatically converted to character pointer, so the function doesn't know how many chars it can store. Actually, the chars was stored one by one like this: ****abcde*** (The star means that something which doesn't belongs to this array.) If you mandatory pass it more than it can store, it will act like this: ****abcdefgh (In fact, it can still store 5 chars, and the "fgh" doesn't belongs to the array.) But, when you try to print the character pointer, it will keep typing until finding a '\0'. All in all, pass a array something more than it can store is a bad choice
17th Apr 2018, 7:38 AM
刘宇轩,一个来自西安的喜欢取长昵称的大学生。
刘宇轩,一个来自西安的喜欢取长昵称的大学生。 - avatar
+ 1
This looks like a bug in the Code Playground. Which needs reporting. Your code should trigger a segmentation fault, when the array bounds are exceeded. Try it outside of Code Playground, in another development environment.
17th Apr 2018, 4:07 AM
Emma
+ 1
It sucks when people copy your answer, and get best answer. Lame questioner. I will continue to call people out on bad etiquette. I won't help you again. That's my choice. Also blocking cheats.
17th Apr 2018, 12:55 PM
Emma
+ 1
Xan I know you don't like me (I don't know why though), but your answer was wrong. It CAN produce a segmentation fault, but that's not a must. It's not a sololearn bug, but an undefined behaviour of the c standard. Nevertheless this is a bad practice to make a code that does that. I know you have a hard time so I won't be mad at you for calling me out with wrong accusations. I hope you feel better soon.
17th Apr 2018, 1:03 PM
Alex
Alex - avatar
0
Xan i tried it in codeblocks same thing happens.
17th Apr 2018, 4:29 AM
Akib
Akib - avatar