Typcast a null pointer to char*
Suppose I have a char* elem
that is supposed to hold a char**
, such that elem[0] = char**
, elem[1...m]= <more chars>
. Is there a way I can put a null ptr within char* elem
? When I try to set elem = NULL
, it gives me a type error because NULL is an 开发者_如何学编程int.
Any help would be greatly appreciated!
If you are looking for a binary 0, try '\0'
That is null termination at the end of a string (char *)
char*
points to a char
, not char*
. Unless your architecture has 8-bit addresses or your characters are way wider than 8-bit, you can't possibly cram pointer into character.
The problem is not NULL
vs. 0
, they are the same and mean null-pointer which is a different concept than arithmetic 0 or binary 0. Your problem is most likely with the definition of your array.
String case (pointer to char):
char *s;
s = malloc(10 * sizeof(char));
s[0] = 'H'; /* set char */
s[1] = NULL; /* not ok */
s[2] = '\0'; /* binary 0, end of string marker */
Pointer of pointer to char:
char **x;
x = malloc(10 * sizeof(char *));
x[0] = "Hello"; /* let it point to string */
x[1] = NULL; /* let it point to nowhere */
x[2] = 0; /* same thing as above */
x[3] = '\0'; /* bad, expects pointer to char not char */
If you have a plain char* foo
variable then foo[0]
will be of type char
so you'll have to set it to \0
(or 0
).
I think you got the pointers mixed up.
char* - string
char ** - address of that string or an array of strings depending on your data
char *** - address of an array of strings.
Try re-reading your assignment maybe you got something wrong.
LE: And what Jeromi mentioned in his comment works.
typedef struct{
char** some_data
}info;
char* info;
If you want some char** to be NULL as some point just initialize your info->some_data to NULL when you allocate memory.
精彩评论