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
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 andarrholds the address of the first character. (thougharris NOT a pointer (notchar *) but of typechar[10])For demonstration:
char *str = "1234556";is like: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.