Furjetur
Furjetur

Reputation: 1

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

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.

Upvotes: 0

Views: 77

Answers (4)

Gopi
Gopi

Reputation: 19874

chmd1[i] = args[i];

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

Upvotes: 1

VolAnd
VolAnd

Reputation: 6407

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
    }

Upvotes: 1

N Kaushik
N Kaushik

Reputation: 2208

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.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206717

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.

Upvotes: 1

Related Questions