Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)

int main()
    char **Str;
    Str= (char**)calloc(20,sizeof(char));
    Str[0]= (char*) calloc(10, sizeof(char));
    Str[0]= "Hello, world";
    printf("%s", *(Str+0));

What I have tried:

When writing char *Str instead of char **Str, program goes wrong so why?
And Why we have just wrote (char**) in first dynamic memory allocation, then writing (char*) in the second one?
Updated 20-Feb-23 4:10am

You allocate a block of memory (20 chars worth) and tell the system that that is a set of pointers to chars - because Str is a pointer to a pointer to a char. Which is effectively a pointer to a string.

Think of Str as a array of pointers to chars (or an array of strings) and it's clearer: Str[0] returns a pointer to a character, as does *Str.

If you replace char** with char* you lose the array of strings in favour of a single string and you code starts to fail.
Share this answer
Andre Oosthuizen 17-Feb-23 9:15am    
Addy__0 17-Feb-23 9:29am    
what is the advantage of using char** instead of char*?
Richard MacCutchan 17-Feb-23 9:54am    
There iss no advantage, they are different things. A char* is used to declare a single pointer that points at an array of characters. When you declare something as char** you are going to use it as an array of pointers to arrays of characters. So when you allocate a char** type it should be
char** list = calloc(20, sizeof(char*));

Now you can assign a char* type to each element of list.
OriginalGriff 17-Feb-23 10:02am    
Beat me to it! :D
Richard MacCutchan 17-Feb-23 11:26am    
If you need the points ... :))
Just keep in mind that everything takes up memory, including pointers. It can be handy to let a pointer (to a pointer) point to something else.

Also, the line where memory is allocated to store the actual string, is not needed.

Str[0]= (char*) calloc(10, sizeof(char)); // Not needed
Str[0]= "Hello, world"; // Str[0] now points to your 'Hello world'

The last line can also be written like this:
printf("%s", Str[0]);

In other words: use the pointer that is stored at index 0.

Sometimes it helps to visualise things. If you search the internet for 'C char pointers explained', you'll find some pictures that may explain things a bit more.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900