-1

When I try to run the following code, the program crashes:

#include <string.h>
#include <stdio.h>

typedef char* String;

int main() {
    char string1[] = "hello";
    void* try = &string1;
    String try2 = *(String*)try;
    printf("%s ",try2);
}

any Idea why?

nalzok
  • 14,965
  • 21
  • 72
  • 139
Eden_Yosef
  • 45
  • 5

5 Answers5

2
String try2 = *(String*)try;

is equivalent to

char* try2 = *(char**)try;

which presumably conflicts to your intention. You should write either

String try2 = try;

or simply

char *try2 = try;

Also note that casting can hide serious problems, so you should avoid using them when they are unnecessary.

nalzok
  • 14,965
  • 21
  • 72
  • 139
1

In your code,

 String try2=*(String*)try;

is wrong. You can get rid of the unnecessary (harmful) casts (which actually hides the issue of mismatched datatype) and simply write

 String try2 = try;
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You can either use

try=&string1[0];

or

try=string1;
cleblanc
  • 3,678
  • 1
  • 13
  • 16
0
String try2=*(String*)try;

is wrong.

You can have either

String try2=(String)try;

or

String try2=try; // Recommended style, since a void* can be safely cast into any other pointer type.
sjsam
  • 21,411
  • 5
  • 55
  • 102
0

The type of string is char[6], it is an array of char, and you can assing it to a char pointer:

char* p = string;

However the type of &string is char(*)[6]. It is a pointer to an array of 6 char, so you cannot assign it to char**, which is a pointer to a pointer to char. You need to assign it to a pointer to an array of 6 characters:

char (*pa)[6] = &string;

Thus the cast you made here:

(String*)try;

which is equivalent to:

( char**)try 

Is incorrect, because try represents a pointer to an array of 6 char, and not a pointer to a pointer to char.

The pointer should be cast to the correct type, a pointer to an array of 6 char:

String* try2 = *( char(*)[6] )try;
2501
  • 25,460
  • 4
  • 47
  • 87