How do I use char** ? (pointer to an array of chars)

Related searches

So I'm trying to make a char**, I fully understand how it works in the background and all that stuff but I don't seem to understand how to write the code for it. I want to make a pointer to an array of chars which has a name in it. I need help with storing a string in it (using strcpy() ) and print it after that.

char** name = (char**)malloc((strlen("MyName") + 1) * sizeof(char*));
strcpy(name, "MyName"); // I get an error right here

If you really want a pointer to an char array, you could do the following:

char** name = (char**)malloc(sizeof(char*)); //initialize the pointer
*name = (char*)malloc((strlen("MyName") + 1) * sizeof(char)); //initialize the array
strcpy(*name, "MyName");

C Strings (Arrays vs. Pointers), However, pointers only hold an address, they cannot hold all the characters in a character array. This means that when we use a char * to keep track of a string,� The type of both the variables is a pointer to char or (char*), so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer. Here are the differences: arr is an array of 12 characters. When compiler sees the statement:

So I'm trying to make a char**, I fully understand how it works in the background and all that stuff but I don't seem to understand how to write the code for it.

Umm... No, not quite.

To declare a pointer-to-char, you simply decalre:

    char *name = malloc (strlen("MyName") + 1);

Why? When you make your call to malloc, malloc allocates a block of memory providing strlen("MyName") + 1 bytes and returns the starting address to that block of memory -- which you assign to name. You then can copy "MyName" to name (with 1-byte remaining for the nul-terminating character). The approach would be:

    size_t len = strlen ("MyName");
    char *name = malloc (len + 1);      /* allocate len + 1 bytes */
    if (name == NULL) {                 /* validate EVERY allocation */
        perror ("malloc-name");
        /* handle error by returning or exiting */
    }
    memcpy (name, "MyName", len + 1);   /* no need to scan again for \0 */

    /* do something with name - here */

    free (name);    /* don't forget to free name when you are done */

What then does char** do?

When you are dealing with a pointer-to-pointer-to-char, you must first allocate for some number of pointers, then you can allocate and assign a block of memory to each of the pointers and use each pointer just as you have used name above.

For example:

    /* array of ponters to string-literals for your source of strings */
    char *band[] = { "George", "Ringo", "Paul", "John" };
    char **names;
    size_t nmembers = sizeof band / sizeof *band;

    /* allocate nmembers pointers */
    names = malloc (nmembers * sizeof *names);
    if (names == NULL) {                /* validate EVERY allocation */
        perror ("malloc-name_pointers");
        /* handle error by returning or exiting */
    }

    /* now loop allocating for each name and copy */
    for (size_t i = 0; i < nmembers; i++) {
        size_t len = strlen (band[i]);      /* get length */
        names[i] = malloc (len + 1);        /* allocate */
        if (names[i] == NULL) {             /* validate EVERY allocation */
            perror ("malloc-names[i]");
            /* handle error by returning or exiting */
        }
        memcpy (names[i], band[i], len + 1);/* no need to scan again for \0 */
    }

    /* output each */
    for (size_t i = 0; i < nmembers; i++)
        printf ("member[%zu]: %s\n", i + 1, names[i]);

Freeing names is a two step process. You must free the memory allocated to each of the names pointers and then free the pointers themselves, e.g.

    for (size_t i = 0; i < nmembers; i++)
        free (names[i]);    /* free each allocated names[i] */
    free (names);           /* free pointers */

Now hopefully you more closely "... fully understand how it works". Let me know if you have any questions.

What is the difference between char array and char pointer in C , char* and char[] are different types, but it's not immediately apparent in all cases. This is because arrays decay into pointers, meaning that if an� There may be a situation, when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer − int *ptr[MAX]; This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value.

First thing you should understand is that declaring a variable as a single pointer or a double pointer (or any other n pointer) doesn't actually tell whether the underlying variable holds a single value or an array of values.

Single pointer points to a memory address on which actual value is stored. Double pointer points to a memory address on which single pointer is stored, and so on.

Now, to make a pointer to an array of char pointers you can use a single char pointer (char*) but I recommend to use double char pointer (char**) for maintainability purposes.

Consider the following code:

char** names = (char**)malloc(100 * sizeof(char*));

It will allocate memory space for 100 char pointers (char*) on heap and return you a double pointer (char**) to the first single pointer (char*) in that memory space. This means you will be able to save 100 char pointers (or 100 names in your case) inside that memory space. Then you can use them like this:

char* name0 = "First Name"; // Saved on stack
char* name1 = malloc((strlen("Second Name") + 1) * sizeof(char));  // Saved on heap
strcpy(name1, "Second Name");

names[0] = name0;
names[1] = name1;

Also, please note that when saving a string on heap you need to add one more place for null character (manually).

What's difference between char s[] and char *s in C?, The statements 'char s[] = “geeksquiz”' creates a character array s is just a pointer and like any other pointer stores address of string literal. Note: Since we assigned the pointer the address of an array of characters, the pointer must be a character pointer--the types must match. Also, to assign the address of an array to a pointer, we do not use the address-of (&) operator since the name of an array (like label) behaves like the address of that array in this context.

Convert string to char array in C++, The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of� Pointer and Character strings. Pointer can also be used to create strings. Pointer variables of char type are treated as string. char *str = "Hello"; The above code creates a string and stores its address in the pointer variable str. The pointer str now points to the first character of the string "Hello".

section 5.5: Character Pointers and Functions, We've said that pointers and arrays are different, and here's another illustration. on the other hand, the string literal is used to create a little block of characters� 1. Using char* Here, str is basically a pointer to the (const)string literal. Syntax: char* str = "This is GeeksForGeeks"; Pros: Only one pointer is required to refer to whole string. That shows this is memory efficient. No need to declare the size of string beforehand.

Declaring Char Array. Declaration of a char array can be done by using square brackets: char[] JavaCharArray; The square brackets can be placed at the end as well. char JavaCharArray[]; The next step is to initialize these arrays. Initializing Char Array. A char array can be initialized by conferring to it a default size. char[] JavaCharArray

Comments
  • Just use one *. With two *, you are declaring an array of pointers, which could be used for an array of strings. BTW, if you're actually writing C code, don't cast the results of malloc. C++ is a different language, and a different rules apply.
  • @user3386109; With two *s he is not declaring an array of pointers but declaring a pointer to pointer to char data type.
  • When you get an error, the first step is to read the error message.
  • @haccks That's a distinction without a difference, since a pointer to a single char is indistinguishable from a pointer to an array of char.
  • @user3386109; Pointer to a char, pointer to an array of char and an array of pointers to char are all different data types. None of the three are compatible with each other.
  • strlen("MyName") + 1 == sizeof("MyName"); strlen of string literal does not have too much sense