Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char* and char** (in C)

Tags:

c

string

pointers

I have written this code which is simple

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

void printLastLetter(char **str)
{
    printf("%c\n",*(*str + strlen(*str) - 1));
    printf("%c\n",**(str + strlen(*str) - 1));
}

int main()
{
    char *str = "1234556";
    printLastLetter(&str);
    return 1;
}

Now, if I want to print the last char in a string I know the first line of printLastLetter is the right line of code. What I don't fully understand is what the difference is between *str and **str. The first one is an array of characters, and the second?? Also, what is the difference in memory allocation between char *str and str[10]? Thnks

like image 269
yotamoo Avatar asked Aug 15 '11 13:08

yotamoo


1 Answers

char* is a pointer to char, char ** is a pointer to a pointer to char.

char *ptr; does NOT allocate memory for characters, it allocates memory for a pointer to char.

char arr[10]; allocates 10 characters and arr holds the address of the first character. (though arr is NOT a pointer (not char *) but of type char[10])

For demonstration: char *str = "1234556"; is like:

char *str;         // allocate a space for char pointer on the stack
str = "1234556";   // assign the address of the string literal "1234556" to str

As @Oli Charlesworth commented, if you use a pointer to a constant string, such as in the above example, you should declare the pointer as const - const char *str = "1234556"; so if you try to modify it, which is not allowed, you will get a compile-time error and not a run-time access violation error, such as segmentation fault. If you're not familiar with that, please look here.

Also see the explanation in the FAQ of newsgroup comp.lang.c.

like image 86
MByD Avatar answered Oct 29 '22 20:10

MByD