Setting a specific element of a char** array to NULL

时间:2015-04-23 05:30:10

标签: c arrays

I am attempting to set the last element in a second char ** array to NULL after I encounter a specific char in the first array.

int test(char ** args){
   char ** chmd1;
   for(int i = 0; args[i] != NULL; ++i){
     if(!strncmp(args[i], "<", 1)){
        chmd1[i] = NULL;
        break;
     }
     chmd1[i] = args[i];
   }

   for(int i = 0; chmd1[i] != NULL; ++i){
      printf("%s", chmd1[i]);
   }

   return 0;
}

This code segfaults as the second for loop goes on for more iterations past where the NULL should be.

I want to be able to be able to do this just by manipulating pointers and not using any mallocs, but I'm completely stuck.

4 个答案:

答案 0 :(得分:1)

This code segfaults as the second for loop goes on for more iterations past where the the NULL should be.

You have not allocated memory for chmd1 and yet you are using it like it points to valid memory.

I want to be able to be able to do this just by manipulating pointers and not using any mallocs, but I'm completely stuck.

You can't do that. You have use malloc (or one of the other functions from the malloc group of functions: calloc, realloc) to allocate memory for chmd1 before you can use it.

答案 1 :(得分:1)

chmd1[i] = args[i];

chmd[i] is a pointer in 2D space and you are not allocating memory for the pointer.

答案 2 :(得分:1)

allocate memory for pointer char ** chmd1;

I want to be able to be able to do this just by manipulating pointers and not using any mallocs, but I'm completely stuck.

Without allocating memory to chmd1, it will not be possible.

答案 3 :(得分:1)

You have to allocate memory for char ** chmd1; before assigning value NULL (or copy elements from args) to any element.

It can be something like

 char ** chmd1 = malloc(NUMBER * sizeof(char*));

or even

 char * chmd1[NUMBER];

To determine NUMBER value find the NULL in the args first.

EDIT:

Also you can use realloc in your loop as:

    char **chmd1 = NULL;
    int i;
    for(i = 0; argv[i] != NULL; ++i){
        chmd1 = (char**)realloc(chmd1, i * sizeof(char*) );
        if(!strncmp(argv[i], "<", 1)){
            chmd1[i] = NULL;
            break;
        }
        chmd1[i] = argv[i];
    }
    // then use i as size of chmd1
    for(int cnt = 0; cnt < i; cnt++)
    {
          if( chmd1[i] == NULL ) ; // do something
    }