Why did you create a pointer to pointer?

+1 Aleksander Olewinski · January 27, 2015
Bucky, can you tell me why this can not look like this one?

int main()
{
    char movie[20];

    fgets(movie, 20, stdin);
    puts(movie);
    getchar();
    return 0;
}

in earliest video you said that name of array is a pointer to it's first element. So what for you creating pointer to pointer?

Thanks 
Alex

Post a Reply

Replies

Oldest  Newest  Rating
+1 Lazar Bulic · January 27, 2015
There are many reasons. Lets answer your question with a quick challenge. User inputs a string with unknown  length. Without the library string.h print the string normally and also in the opposite way.

so for example: 

input:

"I love C"

output:

"I love C"
"C evol I"  
0 Lazar Bulic · January 28, 2015
Student c I think you misunderstood his question. 

As I understand:

Bukcy said that arrays are pointer to the first element in that array, which is correct.

int a[]; This is a pointer to the part to the memory were first element of array is stored. 

Following that why create a pointer to an array.
int a[3],  *pointer;
pointer = a;

In the first example you showed the usage of a double pointers.


And here an example that in most cases its easier to use pointer and better for program:

Without pointer:


#include <stdlib.h>
#include <string.h>

main(){
    char str[100];
    int num;
    gets(str);
    puts(str);
    for(num=strlen(str)-1;num>=0; i--)
        putchar(str[num]);
    return 0; 


With pointer:


#include <stdlib.h>

main(){
    char str[100];
    gets(str);
    char* pointer = str;
    while (*pointer)
        putchar(*pointer++);
    putchar('\n');
    while (--pointer >= str)
        putchar(*pointer);
    return 0;
}


With string declared as pointer: 


#include <stdlib.h>

main(){
    char *str = malloc(100);
    char* pointer = str;
    gets(str);
    while (*pointer)
        putchar(*pointer++);
    putchar('\n');
    while (--pointer >= str)
        putchar(*pointer);
    free(str);
    return 0;
}


The solution with pointer is I think a little bit more efficient then the solution without one.
In 3rd solution I just proved the theory that arrays and string are nothing more than pointers to the first element.

Pointers have many implementations and are really important in my opinion one of the most important things in c. You won't find pointers in higher languages (Java, C#.....) 
For example pointers are really importation when making linked lists and binary trees in c. Also the correct implementation of pointers is what separates good and excellent programmer.

For starters try sting manipulation without pointers. You will find it really hard.
  • 1

C

107,188 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator