MMtn
MMtn

Reputation: 29

Why do char * and char ** have the same value?

I have written this code which is simple, So what I do not understand is why **str1 and **str2 are the same?

Code

#include <stdlib.h>
#include <stdio.h>

int main() {
    char *str1 = "Hey, you";
    char *str2 = malloc(11);
    strcpy(str2, "Hey! You");

    if (*str1 == *str2) {
        printf ("HoHoHo!");
    }

    return 0;
}

Upvotes: 2

Views: 84

Answers (3)

0___________
0___________

Reputation: 68013

the * before the symbol means something completely different in the declaration and in the function body.

int *x; - declares the pointer to the int object

y = *x; - the * dereferences the pointer x it is the opposite to its meaning in the declaration. It takes out one level of indirection, when in the declaration it adds one level.

I think that is reason of your confusion.

in your example if (*str1 == *str2) the * "removes" indirection and the result is the char itself (not the pointer to pointer)

Upvotes: 1

john
john

Reputation: 88017

Nowhere in your code do you have **str1 and **str2. I guess you are asking why is this true if (*str1 == *str2)? That code tests the character pointed to by str1 and str2. Since that's is 'H' in both cases the expression evaluates to true.

If you want to compare C style strings you use strcmp which returns zero if two strings are equal.

if (strcmp(str1, str2) == 0)
{
    printf ("HoHoHo!");
}

Upvotes: 5

selbie
selbie

Reputation: 104589

str1 points to "Hey, you".

str2 points to "Hey! you"

*str1 is the char at that address. Which is essentially the first letter of the string: 'H'. The first letter of str2 is also 'H'. Hence (*str1 == *str2) is a true expression because ('H' == 'H')

To compare two strings:

strcmp(str1, str2) - returns 0 if the same contents, non-zero otherwise.

Upvotes: 4

Related Questions