Reputation: 201
I am writing a C program in Unix and cannot figure out how to set an array element to NULL. I need to be able to do this to remove multiple characters from a string.
Upvotes: 2
Views: 78354
Reputation: 2575
You can't assign null
to specific char array index as value represented by that index is char instead of pointer. But if you need to remove specific character from given string, you can implement this as follows
void removeChar(char *str, char garbage) {
char *src, *dst;
for (src = dst = str; *src != '\0'; src++) {
*dst = *src;
if (*dst != garbage) dst++;
}
*dst = '\0';
}
Test Program
#include<stdio.h>
int main(void) {
char* str = malloc(strlen("abcdef")+1);
strcpy(str, "abcdbbbef");
removeChar(str, 'b');
printf("%s", str);
free(str);
return 0;
}
output
acdef
Upvotes: 7
Reputation: 67745
If you have a char[]
, you can zero-out individual elements using this:
char arr[10] = "foo";
arr[1] = '\0';
Note that this isn't the same as assigning NULL
, since arr[1]
is a char
and not a pointer, you can't assign NULL
to it.
That said, that probably won't do what you think it will. The above example will produce the string f
, not fo
as you seem to expect.
If you want to remove characters from a string, you have to shift the contents of the string to the left (including the null terminator) using memmove
and some pointer arithmetic:
Example:
#include <stdio.h>
#include <string.h>
int removechars(char *str, size_t pos, size_t cnt) {
size_t len = strlen(str);
if (pos + cnt > len)
return -1;
memmove(str + pos, str + pos + cnt, len - pos - cnt + 1);
return 0;
}
Then use it like so:
char str[12] = "hello world";
if (removechars(str, 5, 4) == 0) /* remove 4 chars starting at str[5] */
printf("%s\n", str); /* hellold */
Upvotes: 2
Reputation: 27125
If you're talking about an array of pointers (say char **
), you'd just say array[element] = NULL;
. But it sounds as though you really want to just truncate a string (char *
), in which case you'd actually want to write string[index] = '\0'
, where \0
is the null byte. But, as far as I know, 0
, '\0'
, and NULL
are all equivalent and equal to 0 (please correct me if I'm wrong). Of course, for clarity, you should use 0
for numbers, '\0'
for chars and strings, and NULL
for pointers.
Upvotes: 0