Assasins
Assasins

Reputation: 1633

What does (char* ) do in 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?

Upvotes: 0

Views: 10500

Answers (3)

ThiefMaster
ThiefMaster

Reputation: 318808

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.

Upvotes: 10

Some programmer dude
Some programmer dude

Reputation: 409482

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.

Upvotes: 5

uba
uba

Reputation: 2031

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

Upvotes: 2

Related Questions