What is the size of the double pointer string?

Suppose I have char **argv

. How to determine its size?

I have a string - an example would be: sleep 30 &

which is stored in argv

. I would like to be able to access the last array in *argv

. In this case, the last array contains &

. How can I access it? strlen(argv)

doesn't seem to work as expected. sizeof()

will obviously not work as expected because it **argv

is a pointer.

Note. I'm not talking about **argv

as an argument to main (), so I don't have argc

or any other indicator of how long the string is.

+3


source to share


4 answers


EDIT: Edited to work with a custom array of strings. The pointer NULL

points to the end of the array. While this declares a 4-string array, this method can be used with a dynamically sized array.

#include <stdio.h>

int main()
{
    char* custom[4] = { "sleep", "30", "&", NULL };
    int last;
    for (last = 0; custom[last + 1]; last++);
    printf("%i - %s\n", last, custom[last]);
    return 0;
}

// ./a.out
// > 2 - &

      



For this to work for you, you will need to edit your program to explicitly add an additional line NULL

to your char**

when you create it. Without this indicator, the address after the last line does not have to be NULL

, so you can include garbage in the bill or cause a segmentation fault.

+5


source


Passing in a counter like argc is the most common usage, but you say you don't have that.

Then the usual way is to have the last element of argv point to NULL to indicate that it is the last element of the array.



int argc = 0;
while (*argv++) {
 argc++;
}

      

0


source


You may need to use strtok

to tokenize the arguments and work with them to the last.

Referemce for strtok .

0


source


   char *argv[] = {"abc","123","xya"};

    //prints the last string
   printf("%s",a[strlen(*a)-1]);

      

// if you are sure the string array is null terminated

   char *temp = 0 ;
   while(*argv){
        temp = *argv;
        (*argv)++;
   }
  //temp has the last string

      

0


source







All Articles