What does (char* ) do in C? - c

What does (char* )str do in the below code?
/**
* Main file
*/
#include <assert.h>
#include <mylib.h>
int main()
{
const char str[] = "this is my first lab\n";
int ret=1;
ret = my_print((char *)str, sizeof(str));
assert(!ret);
return 0;
}
This code is written by my instructor.
my_print is a function which receives a pointer to a string and the size of that string. I am confused on why do we have to use (char *)str to pass the string to the my_print function. What does it actually do?

It casts away the const.
This means it makes your program likely to crash in case my_print modifies that string since its memory may be marked as read-only. So it's generally a bad idea to remove the const modifier through a cast.
In your case it looks a bit like whoever implemented my_print didn't think that string to be printed would never have to be modified and thus didn't make it accept a const char * argument.
So what you should do instead of the cast is changing the definition of my_print to accept a const char * instead of a char * as its first parameter.

That is "type casting" (or "type conversion"). In other words, it tells the compiler to treat one type as another type.
What this specific conversion does is tell the compiler to treat the constant string as not constant. If the called function tries to modify the string, it may not work, or may even crash the program, as modifying constant data is undefined behavior.

It is a typecast, i.e. it changes the datatype. (char*) means type cast to type "pointer to char"

Related

Why we didn't use * during dereferencing the pointer?

In the below code, we get a pointer from strdup(source) and we store it in a pointer named target.
Now, when we print the string using pointer, we don't add * at the beginning of the pointer: why is it so? As I studied whenever we want to dereference any pointer we use *pointer_name. If we add * in the below code, we get an error.
I am very beginner, so pls ans in easy words.
#include<stdio.h>
#include<string.h>
int main()
{
char source[] = "Programming";
char* target = strdup(source);
printf("%s\n",target);
return 0;
}
printf expects a char pointer in the place of the %s specifier.
https://en.cppreference.com/w/c/io/fprintf
char* target = strdup(source);
printf("%s\n",target);
Why we don't use *target in the code above?
The explanation is quite simple, as already stated in previous answers: target has type char pointer, which is exactly what printf() wants in the above call.
Now, printf() is a little complicated because its semantic is not simple - basically it accepts zero or more arguments after the first, of any type (possibly applying promotion). But if we use strdup() again, maybe it is simpler:
char* target2 = strdup(target);
Here, if you wrote strdup(*target), the compiler might warn that you are passing a char instead of a pointer to char.
strdup() returns a char*, hence the char* type of target. target holds a pointer to the first character in an array of chars. printf("%s", string) expects string to be a char*, so there’s no reason to do anything to target; just pass it to printf().
If you dereferenced target, you would get a single char (P in this case). printf() would then complain that you had supplied a character instead of a string (pointer to character). Even worse, the program could compile, and then printf() would try to print the string at address P (0x50), which would result in probably unwanted behaviour.
When working with arrays—a string is a type of array—you rarely want to dereference the array.

Why in the prototype of strcpy() function one parameter is of constant type? [duplicate]

I implemented my own strcpys to find if there is any difference between src as const char* & char *, but don't find any difference between the following 2 & both worked the same.
char * my_strcpy(char*dest, char* src)
{
while ('\0' != *src)
*dest++ = *src++;
*dest++ = '\0';
return dest;
}
char * my_strcpy2(char*dest, const char* src)
{
while ('\0' != *src)
*dest++ = *src++;
*dest++ = '\0';
return dest;
}
Is there any reason that the strcpy takes the source pointer as const char* instead of char*?
Is there any reason that the strcpy takes the source pointer as char* instead of const char*?
The source pointer should be const char *. The reason is common for all functions (not just strcpy) that do not intend to change the source accidentally inside the function.
The practice applies to both library functions like strcpy or your own custom functions. As with library function like strcpy there is no chance that the source is accidentially changed. But for your own (or everyone else) custom function, anything can happen. And if you do modify it accidentially, then you would get a compile error telling you so. And that's when the const is making a difference.
"don't find any difference between the following 2" -- what could the differences be, in your wildest dreams?
The only difference the const declaration has is on the caller side. By the const parameter declaration the function promises not to change the memory accessed through the pointer. It promises only to read through it, which is consistent with the semantics of strcpy(). (Note: Whether the function actually does not write through the pointer is not guaranteed at all. But it promises.)
The caller can therefore call the function with a pointer to constant data and assume that the function will not attempt to write to it.
That is important syntactically, logically and materially:
The language permits the caller to provide a pointer to const data as the argument (it would not allow that for your first non-const version).
The caller can be sure that sensitive data is not altered inside the function as a side effect; imagine a pointer into kernel data structures here. (Counter-example: strtok() writes to the original string, which is therefore not declared const!)
The data may be physically read-only (like, it may be burned into the ROM of a controller), so that an attempt to write to it would cause, well, to quote the excellent Max Barry: a "catastrophic system failure. (...) I'm not saying it's a big deal."
For starters function strcpy returns pointer to the destination string. Your function should also return pointer to the destination string. It is a common convention for functions that process strings in the C Standard.
So the function can look the following way
char * my_strcpy( char *dest, const char *src )
{
char *p = dest;
while ( *p++ = *src++ );
return dest;
}
In this case it can be called for example the following way
const char *hello = "Hello, World!";
char s[14];
puts( s, hello );
Specifying the second parameter of the function as a pointer to a constant character string means 1) that the function guarantees that it will not change the pointed string and 2) allows to pass to the function constant strings.
A pointer to a non-constant object can be implicitly converted to a pointer to constant object. The reverse operation is not allowed without explicit casting.
So if the parameter is declared like pointer to a constant string then you can pass non-constant strings along with constant strings to the same function as arguments. Otherwise the function can not be called with constant strings because the compiler will issue an error saying that it unable to convert an object of type const char * to an object of type char *.

When are values implicitly converted to pointers?

I have many functions like:
void write(char* param, int len)
{
//
}
And I notice that I almost never use the & operator for arguments. When I pass an array:
char in[20];
write(in, 20);
I dont need it, but when I pass a single value:
write(5, 1);
I don't seem to need it, and when I pass a pointer:
char* in = malloc(20);
write(in, 20);
I also dont need it. So in which circumstances do I actually need to call:
write(&in, 1);
Because I'm confused :D
Are you sure about your second case? It doesn't compile for me and should be
char in = 5;
write(&in, 1);
When are values implicitly converted to pointers?
In practice, integer types may be converted to pointers implicitly by the compiler. In theory, this is illegal and compilers that accept it will usually issue a warning:
example.c:2:6: warning: incompatible integer to pointer conversion initializing
'void *' with an expression of type 'int'
In your above example:
char in = 5;
write(in, 20);
char is an integer type, so if your compiler allows it, it may be implicitly converted to a pointer type, although it is not part of the C standard and is completely compiler-specific.
Note that converting an integer type to a pointer type using a cast is allowed by the standard, although results are implementation-defined:
char in = 5;
write((char *)in, 20);
The only allowed case of implicit conversion is when integer constant 0, which denotes a null pointer:
write(0, 20); // allowed
Note that the integer constant is itself allowed, but a variable of integer type with the value 0 is not:
char in = 0;
write(in, 20); // not allowed
As for the others, when you pass a pointer, you don't need the &, obviously, because it's already a pointer. When you pass an array, it decays to a pointer so you don't need & there either. In both these cases it would be actually illegal to use it, as your function above expects a char * and be fed with a char ** and a char (*)[20] respectively.
If you copy somehow the prototype of function 'write' to the file where you call this function, as follows.
void write(char *in, int len);
void foo(int bar){
char in=5;
write(in, 1);
}
You will probably get a warning. Because in is not a pointer, though 5 can be an address.
I guess if your program is compiled and linked successfully, it will crash at run-time.
with using;
return_type function_name(prim_data_type* param...)
param is a pointer that pointing an address in the memory and *param is the value in that address.
Answer is about what you want to do with this param.
char in[20];
by saying that "in" is the first element's address. So at the function call:
write(in, 20);
you are sending the first element's address so in the function implementation, you can access the first element by *param, second element with *(param+1) or param[1] etc.
The place that you are confused is here:
char in = 5;
write(in, 1);
Because in is the address 5 (00000005), so in the implementation of the function you are accessing that place whichever value is there. You must be careful with using like this.
In the malloc operation:
char* in = malloc(20);
write(in, 20);
in is a pointer to an address (first element's address) holding up 20 elements of char can be take space. In the function you can access to all elements with param pointer(*param is the first element, *(param+7) or param[7] is the 8. element)
In the conclusion, when you want to play with an primary data typed variable (int, float, char..) in another function, you must use;
write(&in);
By doing that, in the implementation of that write function, you can access that variable, change the value by *param with no confusion.
Note:Some explanations were simplified here for better understanding. Extra warnings would be welcomed here.
Functions and arrays decay into pointers in some contexts. Functions can decay into pointers to functions, and arrays can decay into a pointer to the first element of the array. No other types behave this way.
This example:
char in = 5;
write(in, 1);
Is wrong though. You definitely need the & in that case. Are you sure it worked like that?

char* vs const char* as a parameter

There are many times that I get compile errors when I use char* instead of const char*. So, I am not sure the actual difference, the syntax and the compile mechanism.
If you're after the difference between the two, just think of them as:
char* is a pointer that points to a location containing a value of type char that can also be changed. The pointer's value can be changed, i.e. the pointer can be modified to point to different locations.
const char* is a pointer, whose value can be also changed, that points to a location containing a value of type char that cannot be changed.
const char * means "pointer to an unmodifiable character." It's usually used for strings of characters that shouldn't be modified.
Say you're writing this function:
int checkForMatch(const char * pstr)
You've promised (through the function signature) that you will not change the thing pointed to by pstr. Now say part of checking for a match would involve ignore the case of letters, and you tried to do it by converting the string to upper case before doing your other checks:
strupr(pstr);
You'll get an error saying you can't do that, because strupr is declared as:
char * strupr(char* str);
...and that means it wants to be able to write to the string. You can't write to the characters in a const char * (that's what the const is for).
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's not a safe thing to do (passing something that isn't meant to be modified into something that may modify it).
Of course, this is C, and you can do just about anything in C, including explicitly casting a const char * to a char * — but that would be a really, really bad idea because there is (presumably) some reason that the thing being pointed to by the pointer is const.
char *       : non-constant pointer to non-constant character
const char *    : non-constant pointer to constant   character
char *const     : constant   pointer to non-constant character
const char * const : constant   pointer to constant   character
Reference [link]
I always try to define parameters with const char* not char* because converting from std::string to conts char* is easy by .c_str() method. However converting std::string to char* is not that easy.
Probably I'm too picky. In my book, the character(s) pointed to by a const char* can possibly be changed but not via the const char*. A const char * can point to modifiable storage. Example:
char a[] = "abracadabra";
const char * ccp = &a[0]; // ccp points to modifiable storage.
*&a[0] = 'o'; // This writes to a location pointed to by const char* ccp
So, my wording is:
A char * is a pointer that be changed and that also allows writing through it when dereferenced via * or [].
A const char * is a pointer that be changed and that does not allow writing through it when dereferenced via * or [].

Why am I able to change the contents of const char *ptr?

I passed a pointer ptr to a function whose prototype takes it as const.
foo( const char *str );
Which according to my understanding means that it will not be able to change the contents of ptr passed. Like in the case of foo( const int i ). If foo() tries to chnage the value of i, compiler gives error.
But here I see that it can change the contents of ptr easily.
Please have a look at the following code
foo( const char *str )
{
strcpy( str, "ABC" ) ;
printf( "%s(): %s\n" , __func__ , str ) ;
}
main()
{
char ptr[ ] = "Its just to fill the space" ;
printf( "%s(): %s\n" , __func__ , ptr ) ;
foo( const ptr ) ;
printf( "%s(): %s\n" , __func__ , ptr ) ;
return;
}
On compilation, I only get a warning, no error:
warning: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type
and when I run it, I get an output instead of Segmentation Fault
main(): Its just to fill the space
foo(): ABC
main(): ABC
Now, my questions is
1- What does const char *str in prototype actually means?
Does this mean that function cannot change the contents of str? If that is so then how come the above program changes the value?
2- How can I make sure that the contents of the pointer I have passed will not be changed?
From "contents of the pointer" in the above stated question, I mean "contents of the memory pointed at by the pointer", not "address contained in the pointer".
Edit
Most replies say that this is because of strcpy and C implicit type conversion. But now I tried this
foo( const char *str )
{
str = "Tim" ;
// strcpy( str, "ABC" ) ;
printf( "%s(): %s\n" , __func__ , str ) ;
}
This time the output is, with no warning from compiler
main(): Its just to fill the space
foo(): Tim
main(): Its just to fill the space
So apparently, memory pointed to by str is changed to the memory location containing "Tim" while its in foo(). Although I didn't use strcpy() this time.
Is not const supposed to stop this? or my understanding is wrong?
To me it seems that even with const, I can change the memory reference and the contents of memory reference too. Then what is the use?
Can you give me an example where complier will give me error that I am trying to change a const pointer?
Thanks to all of you for your time and effort.
Your understanding is correct, const char* is a contract that means you can't change memory through this particular pointer.
The problem is that C is very lax with type conversions. strcpy takes a pointer to non-const char, and it is implicitly converted from const char* to char* (as compiler helpfully tells you). You could as easily pass an integer instead of pointer. As a result, your function can't change content pointed by ptr, but strcpy can, because it sees a non-const pointer. You don't get a crash, because in your case, the pointer points to an actual buffer of sufficient size, not a read-only string literal.
To avoid this, look for compiler warnings, or compile, for example, with -Wall -Werror (if you are using gcc).
This behaviour is specific to C. C++, for example, does not allow that, and requires an explicit cast (C-style cast or a const_cast) to strip const qualifier, as you would reasonably expect.
Answer to the extended question
You are assigning a string literal into a non-const char, which, unfortunately, is legal in C and even C++! It is implicitly converted to char*, even though writing through this pointer will now result in undefined behaviour. It is a deprecated feature, and only C++0x so far does not allow this to happen.
With that said, In order to stop changing the pointer itself, you have to declare it as const pointer to char (char *const). Or, if you want to make it that both the contents pointed by it and the pointer itself don't change, use a const pointer to const char (const char * const).
Examples:
void foo (
char *a,
const char *b,
char *const c,
const char *const d)
{
char buf[10];
a = buf; /* OK, changing the pointer */
*a = 'a'; /* OK, changing contents pointed by pointer */
b = buf; /* OK, changing the pointer */
*b = 'b'; /* error, changing contents pointed by pointer */
c = buf; /* error, changing pointer */
*c = 'c'; /* OK, changing contents pointed by pointer */
d = buf; /* error, changing pointer */
*d = 'd'; /* error, changing contents pointed by pointer */
}
For all error lines GCC gives me "error: assignment of read-only location".
"const" is really a compile-time thing, so don't expect a segfault unless the pointer points to some invalid memory. When using const pointers in a way that could potentially alter whatever they point to (in this case passing it to strcpy which accepts non-const), will generate a warning.
1- What does const char *str in prototype actually means?
Does this mean that function cannot change the contents of str?
Yes! This means we cannot change the contents of something(either a char or an array of chars) pointed to by str.
If that is so then how come the above program changes the value?
Thats because strcpy()'s prototype is char * strcpy ( char * destination, const char * source );
In your code there is an implicit conversion from const char* to char* type because strcpy() requires its first argument to be of the type char*.
Technically speaking your code is incorrect rather dangerous. If you try the same code in C++ you'll surely get an error. C++ doesn't allow such implicit conversions but C does.
IIRC the const means that the value of the parameter may not be changed. I your case, the value is the address the pointer points to. strcpy doesn't change the address the pointer points to, but the memory the pointer points to.
Using const here makes sure that the memory reference (address) isn't changed. The memory referenced may be changed, however. This is what's happening here. Assigning a new address to the pointer would result in an error.
SIDE NOTE
I'd consider your foo method insecure. You'd better pass the maximum length of str as well and perform a length check, otherwise you'll be open for buffer overflows.
EDIT
I took the following from this site:
The const char *Str tells the compiler
that the DATA the pointer points too
is const. This means, Str can be
changed within Func, but *Str cannot.
As a copy of the pointer is passed to
Func, any changes made to Str are not
seen by main....
const char* is the same as char const* and not char* const. So this means a pointer to something you can't change.
Elaborating after your edit. The first form inhibits the data to be changed (unless you cast implicitly or explicitly) the second inhibits the pointer itself to be changed.
What you do in your edited version is to change the pointer. This is legal here. If you'd inhibit both you'd have to write char const* const.

Resources