C Char pointers

后端 未结 4 1880
旧时难觅i
旧时难觅i 2021-01-19 15:49

Let us say we have a array of pointers:

char *ptr[30];

Now this works fine, and doesn\'t seems to do anything unexpected! I can input names easi

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 16:43

    The pointer cannot be used that way. It might "work" for you sometimes by sheer chance, but using a pointer without allocating memory for it will cause undefined behavior - meaning that your program may behave erratically and give you unexpected results.

    Remember, just because your program compiles and runs doesn't mean it is correct. In the C language there is a whole class of errors known as "undefined behavior", many of which the compiler will happily let you do without complaining. These include overwriting a buffer, using an uninitialized variable, or dereferencing a pointer that doesn't point to a legitimately allocated memory block. Programs that exhibit undefined behavior may even appear to work normally sometimes - but they are usually very unstable and prone to crash.

提交回复
热议问题