Search and erase char array - c

I am trying to parse through an array for a char and delete everything after that. I did write the code to find the location of the char search in the array. How to delete the remaining part of the array after the identified location. Thank you

You can use memset:
memset(&arr[current_location], 0, sizeof(arr) - current_location);
To set all bytes in arr after current_location contain 0

In C the easiest way to do it is like this:
str[end_idx] = '\0';
This cuts off the string at a particular index because C strings are null terminated.

Related

Replacing specific letters from a string array

I have the following array
char myArray[] = {"H4w6m1ny6pr4gr1mm2rs6d42s63t6t1k26t46ch1ng2616l3ght6b5lb?6N4n2,6th1t’s616h1rdw1r26pr4bl2m"};
and want to replace specific characters from it, H to 1, or all m's to J.
I know I have to use a loop, but how do I do to replace multiple letters with whatever I want? I could go and myArray[0] = 'J' but replacing each position individually doesn't seem efficient to me. Any ideas?

Is it good practise to include an index for an array in C?

I have an array in C that stores strings, and I need to be able to dynamically append to this array. Is it good practise to store the index of this array in a separate variable, or is there some better way to do this? Here's my code.
First defining these variables
char x[10][10];
int x_index = 0;
Adding strings to this array
strcpy(x[x_index], "hello");
x_index += 1;
strcpy(x[x_index], "world");
x_index += 1;
You should call the index the length of the array, because what it is: It is the number of valid entries in the array. There are other entries, but they shouldn't be accessed.
It is not only good practice, but in the most cases necessary to keep track of the current size. Otherwise, how would you know ehere to append the next item? In C, this must be done with an extra variable. (Make sure that you can see that array and length belong together with a consistent nomenclature.)
Make sure that the length doesn't exceed the size of the array, 10 in your example. Often, you have to track both, the length and the size, where the size can be a compile-time constant
if (xlen < XSIZE) strcpy(x[xlen++], str);
(You must also take care not to overflow the 10-character buffer, of course.)
For arrays in which you need to parse every element anyways (and only parse, with no insertion), it is better to put a special value at the end of the array, such as '\0' in char arrays in order to tell the parsing loop when to stop.

Simulating an appendable array in C...Kinda

I'm trying to write a C code that does what a chunk of python code I have written does.
I tried to keep all its lines simple, but there still turns out to be some stuff I wrote that C cannot do.
My code will take an array of coordinates and replace/add items to that array over time.
For example:
[[[0,1]],[[2,1],[1,14]],[[1,1]]] ==> [[[0,1]],[[2,1],[1,14],[3,2]],[[1,1]]]
or
[[[0,1]],[[2,1],[1,14]],[[1,1]]] ==> [[[0,1]],[[40]],[[1,1]]]
I think this is impossible in C, but how about instead using strings to represent the lists so they can be added to? Like this:
[['0$1$'],['2$1$1$14$'],['1$1$']] ==> [['0$1$'],['2$1$1$14$3$2'],['1$1$']]
and
[['0$1$'],['2$1$1$14$'],['1$1$']] ==> [['0$1$'],['40$'],['1$1$']]
In my code, I know each array in the array is either one or more pairs of numbers or just one number so this method works for me.
Can C do this and if so please provide an example.
If you know that both the length of a string and the number of said strings won't exceed a certain value, you can do this:
char Strings[NUMBER_OF_STRINGS][MAX_STRING_LENGTH + 1]; // for the null terminator
It would then be a good practice to zero all this memory:
for (size_t i = 0; i < NUMBER_OF_STRINGS; i++)
memset(Strings[i], 0, MAX_STRING_LENGTH + 1);
And if you want to append a string, use strcat:
strcat(Strings[i], SourceString);
A safer (though slightly more costly since you need to call strlen which walks the entire string) solution would be:
strncat(Strings[i], SourceString, MAX_STRING_LENGTH - strlen(Strings[i]));

Storing one value for each item in 2-Dimensional array

Luckily I came up with a decent title, describing what I was curious about.
While this is really hard for me to explain, I am doing my best.
I tried, storing values in 3D array as such:
char arr[10][10][1];
To copy a string I have to do it in arr[y][x], (And I sadly I can't in just arr[y])but then, because of a reason still unknown for me, I could overflow the buffer with arr[8][8][8]. Maybe because of the size of char** but anyway.
I couldn't find a slot to store a character for each item (x and y)
I tried, it the other way:
char arr[1][10][10];
Assuming that I have 1 item * x and y.
To store a string, I have to do it in arr[0][y], which means the 3rd cell will be a character from the string.
So as a resume, I am trying to store one value for each character in x and y.
Do I really need 4D array for this?
Additional clarification:
I am aware what 1D and 2D arrays are for. Seems I can't understand the 3D array.
I thought that I can store an additional item for each character at y or x.
Example:
char arr[y][x][z];
Where y is the line, x is the column and z is the additional item that applies to all the characters.
A string is an array of characters. An array of strings is therefore an array of arrays of characters. Why you think you need the 3rd dimension, I have no idea.
When you allocate a multi-dimensional array statically, you must specify the maximum number of items that it can contain. In this case, you must specify how many bytes long the string is allowed to be, including one byte for null termination. This is the right-most [] in the expression, in your case 1 byte.
So you haven't actually allocated any memory at all to store a string: 1 byte is enough to store the null termination and nothing else. This is why you get a crash/seg fault when you attempt [x][y][z] when z is any other value than 0. And you cannot store anything meaningful there either.
Size of char** has absolutely nothing to do with this whatsoever. Pointers are not arrays.
I'd strongly suggest that your study this C FAQ about pointers and arrays.
Now what you probably want to do is something like this:
char string_array [10][20+1]; // 10 strings each containing 20 letters + null
strcpy(string_array[0], "hello");
strcpy(string_array[1], "world");
...
printf("%s\n", string_array[0]);
printf("%s\n", string_array[1]);
...
No need for the 3rd dimension as such .
you can use for example a[x][y];
and you can access this using *a[];
As you can also see that while using command line arguments where 2D array *argv[] is used to store a number of strings from command line. It explains you the best how 2D arrays are used.
For further reference you can have a look at this http://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm

clearing a char array c

I thought by setting the first element to a null would clear the entire contents of a char array.
char my_custom_data[40] = "Hello!";
my_custom_data[0] = '\0';
However, this only sets the first element to null.
or
my_custom_data[0] = 0;
rather than use memset, I thought the 2 examples above should clear all the data.
It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset is probably the most effective way to achieve this.
On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.
An array in C is just a memory location, so indeed, your my_custom_data[0] = '\0'; assignment simply sets the first element to zero and leaves the other elements intact.
If you want to clear all the elements of the array, you'll have to visit each element. That is what memset is for:
memset(&arr[0], 0, sizeof(arr));
This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:
char *begin = &arr;
char *end = begin + sizeof(arr);
std::fill(begin, end, 0);
Why would you think setting a single element would clear the entire array?
In C, especially, little ever happens without the programmer explicitly programming it. If you set the first element to zero (or any value), then you have done exactly that, and nothing more.
When initializing you can set an array to zero:
char mcd[40] = {0}; /* sets the whole array */
Otherwise, I don't know any technique other than memset, or something similar.
Use:
memset(my_custom_data, 0, sizeof(my_custom_data));
Or:
memset(my_custom_data, 0, strlen(my_custom_data));
Try the following code:
void clean(char *var) {
int i = 0;
while(var[i] != '\0') {
var[i] = '\0';
i++;
}
}
Why not use memset()? That's how to do it.
Setting the first element leaves the rest of the memory untouched, but str functions will treat the data as empty.
Pls find below where I have explained with data in the array after case 1 & case 2.
char sc_ArrData[ 100 ];
strcpy(sc_ArrData,"Hai" );
Case 1:
sc_ArrData[0] = '\0';
Result:
- "sc_ArrData"
[0] 0 ''
[1] 97 'a'
[2] 105 'i'
[3] 0 ''
Case 2:
memset(&sc_ArrData[0], 0, sizeof(sc_ArrData));
Result:
- "sc_ArrData"
[0] 0 ''
[1] 0 ''
[2] 0 ''
[3] 0 ''
Though setting first argument to NULL will do the trick, using memset is advisable
I usually just do like this:
memset(bufferar, '\0', sizeof(bufferar));
Nope. All you are doing is setting the first value to '\0' or 0.
If you are working with null terminated strings, then in the first example, you'll get behavior that mimics what you expect, however the memory is still set.
If you want to clear the memory without using memset, use a for loop.
You should use memset. Setting just the first element won't work, you need to set all elements - if not, how could you set only the first element to 0?
Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you'll need to use memset.
I thought by setting the first element
to a null would clear the entire
contents of a char array.
That is not correct as you discovered
However, this only sets the first
element to null.
Exactly!
You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.
However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory
set the first element to NULL. printing the char array will give you nothing back.
How about the following:
bzero(my_custom_data,40);
void clearArray (char *input[]){
*input = ' ';
}
Try the following:
strcpy(my_custom_data,"");

Resources