0

I have two multi dimensional char arrays. They may have duplicates. I want to clear the duplicates in the second one. will assigning the particular element in the second array to NULL, clears it or should I assign it to a "/0".

for(i=0; i<10; i++){
   for(j=0; j<10; j++){
      if(!strcmp(a[x][i], b[x][j])){
      b[x][j]=NULL;
   }
   i++;
}

Please give me your inputs.

6
  • 3
    You are missing a } to make the code compile. What's the intent of the i++ in the loop body? Commented Apr 29, 2013 at 18:32
  • '/0' is more portable. Commented Apr 29, 2013 at 18:36
  • 2
    Why on earth would '\0' be more portable? Commented Apr 29, 2013 at 18:41
  • I perfer '\0' over NULL if you are assigning to a single char. Assign NULL to a single char can be confused with assigning to the c-string's pointer. Commented Apr 29, 2013 at 18:43
  • Can you provide an example of what you're thinking? Does "clear a particular element" mean you want to remove a single char from a char array (one letter from a string), or remove a char array from an array of char arrays (a whole string from an array of strings)? Commented Apr 29, 2013 at 19:12

1 Answer 1

1

That really depends on a lot of things.

Are the strings malloc'ed? If they are you should probably free them and set the pointer to NULL. And then when you pass the cleaned up array, you need to check if the string is NULL, before you do what ever you need to do with it.

If the strings are static, or if you don't want to free them, because they are used else where, then you can set them to either NULL or '\0'. If you choose the later, then you should check for strlen(s) == 0 or if s[0] == '\0'.

The thing is, you can do either, it probably doesn't mean much which you choose.

Edit

I'll clarify a bit.

What you need to do depends on whether you have an of arrays of char's (which is '\0' terminated) or an array of pointers to strings.

In the first case, if you want to "remove" a string, you can either change all the character in the array to '\0', or just the first. And use strlen or `s[0] == '\0' to determine if the string is empty.

In the second case, you should free the pointer, and set it to NULL. To check if the string is "empty", test for NULL.

The difference lies in the relationship between pointers and arrays in C, which is not trivial, see here.

Sign up to request clarification or add additional context in comments.

2 Comments

the strings are static. So, if my 5 th element is duplicate and I make it NULL,then I have other 9 elements does my strlen change?
if I assign it to '\0' or NULL its throwing an error "incompatible types in assignment" please help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.