Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Char pointers

Tags:

c

char

pointers

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 easily.

scanf("%s", ptr[1]);
scanf("%s", ptr[2]);
scanf("%s", ptr[3]);

printf("%s\n", ptr[1]);
printf("%s\n", ptr[2]);
printf("%s\n", ptr[3]);

My question is if a pointer can be used in this way to store end number of names, then why is malloc used.? and in this case ptr[1] does not point to the character in the input but to a new input itself. for eg if ptr has mukul, ptr[1] should point to 'u' and if space is not allocated when a pointer is declared like this, what are the limits.?

like image 223
Mukul Shukla Avatar asked Nov 29 '22 17:11

Mukul Shukla


2 Answers

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.

like image 141
Charles Salvia Avatar answered Dec 01 '22 08:12

Charles Salvia


If you use what is in your example, you just owerwrite other locations what come after your ptr array. Most compilers should actually give at least a warning. Your program would crash on most systems, you were just very lucky.

like image 41
vsz Avatar answered Dec 01 '22 08:12

vsz