Access violation with strcat() - c

In my code i have a for loop to concat char by char from another array starting from a certain point. So for example if the text is "hi i need help" and my starting index is 10 it would concat "help" to the end of char* rs.
for (int l = start_index; l < strlen(text); l++) {
strcat(rs, "h");
}
I tested the above and it works fine with no errors, but this
for (int l = start_index; l < strlen(text); l++) {
strcat(rs, text[l]);
}
does not. According to the debugger "text" is char[256] and "rs" is a *char if that helps. The debugger also shows text[l] is of the correct value in that enumeration.

The strcat function takes two strings (pointers to char) as arguments. From the context it seems that text[l] is a single char which can't be used.
One way to work around that is to create a small one-character temporary string for the character:
for (int l = start_index; l < strlen(text); l++) {
char temp[] = { text[l], '\0' }; // Don't forget the terminator
strcat(rs, temp);
}
Another solution is to not use strcat at all, and instead use indexing of the rs string to assign directly to the elements of the string:
size_t end_of_rs = strlen(rs);
for (int l = start_index; l < strlen(text); l++) {
rs[end_of_rs++] = text[l];
}
rs[end_of_rs] = '\0'; // Make sure string is terminated
Or a much simpler solution: Concatenate directly from text:
strcat(rs, &text[start_index]);
But for this you should make sure that start_index isn't beyond the end of text (i.e. you need to verify that start_index < strlen(text)).

Related

How to convert using atoi and strtok with multidimesional arrays?

Okay so i have this mltidim array filled with these numbers,
i wish to convert them into ints at the locations
So its gonna be a int multidim arrayint intarray[2][5][12];
Any tip on getting the converter to solve the issue? ive been on this problem a while and it
feels like im close!!
char chararray[2][5][40] =
{
{
{"307,07,33,307,11,44,307,12,31,307,16,10"},
{"308,07,52,308,11,52,308,12,35,308,16,18"},
{"309,07,24,309,11,40,309,12,30,309,16,14"},
{"310,07,15,310,11,38,310,12,36,310,16,27"},
{"311,07,12,311,11,47,311,12,30,311,16,12"}
},
{
{"314,07,12,314,11,34,314,12,27,314,16,52"},
{"315,07,15,315,11,49,315,12,31,315,16,13"},
{"316,07,59,316,11,44,316,12,38,316,16,42"},
{"317,07,52,317,11,41,317,12,30,317,16,12"},
{"318,08,03,318,11,32,318,12,39,318,16,07"}
}
};
And this is how i am trying to convert but it doesnt even let me debug just a weird error pops up..
int intarray[2][5][12];
for(int i = 0; i < 2 ; i++){
for(int j = 0; j < 5;j++){
for(int k = 0; k < 40;k++){
intarray[i][j][k] = atoi(strtok(chararray[i][j][k],","));
}
}
}
intarray[i][j][k] for i==0, j==0, k==0, represents 3 which is the the character residing at intarray[0][0][0]. This is a single char and cannot be processed using strtok().
What you really want to pass to strtok() is a complete null terminated string:
char chararray[0][0]
which is the 40 character buffer containing "307,07,33,307,11,44,307,12,31,307,16,10".
But because you probably do not want to destroy the array, you should start of by getting a duplicate of the string, something like this:
int intarray[2][5][12] = {{0}};//zero before using
int i=0;
char *dup = strdup(chararray[0][0]);//in your actual code this will be in
//a loop of `i,j` indexes, each one
//yielding the character buffers:
//{"307,07,33,307,11,44,307,12,31,307,16,10"},
//{"308,07,52,308,11,52,308,12,35,308,16,18"},
//{"309,07,24,309,11,40,309,12,30,309,16,14"},
//{"310,07,15,310,11,38,310,12,36,310,16,27"},
//{"311,07,12,311,11,47,311,12,30,311,16,12"}
//{"314,07,12,314,11,34,314,12,27,314,16,52"},
//{"315,07,15,315,11,49,315,12,31,315,16,13"},
//{"316,07,59,316,11,44,316,12,38,316,16,42"},
//{"317,07,52,317,11,41,317,12,30,317,16,12"},
//{"318,08,03,318,11,32,318,12,39,318,16,07"}
if(dup)
{
tok = strtok(dup, ",\n");
while(tok)
{
intarray[0][0][i] = atoi(tok);
tok = strtok(NULL, ",\n");
i++;
}
free(dup);//so you can use it again and again for the other sub-strings.
....
Following this approach, all of the other strings can be parsed into intarray
Each chararray[i][j] is a string - chararray[i][j][k] is a single character in that string. Unfortunately, you're passing the single character to strtok when it expects the address of the first element of the string.
When you're tokenizing repeated elements in a string, you only pass the base address once, then pass NULL for the remainder of the string. So your loop would need to be
for(int i = 0; i < 2 ; i++){
for(int j = 0; j < 5;j++){
intarray[i][j][0] = atoi( strtok( chararray[i][j], "," ) );
for(int k = 1; k < 40;k++){
intarray[i][j][k] = atoi( strtok( NULL, "," ) );
}
}
}
Note that this assumes your input is always well-formed - there's no sort of error or sanity checking.

How to add space between every characters using C

I want a space between every character of a string like I will give input "HELLO"
the result will be "H E L L O"
I need help in that
[Edit from comments]
I want it in a string
for (i = 0; i <= strlen(str); i++) {
printf("\n String is: %s", str[i]);
printf(" ");
}
The shorter, more general answer is that you need to bump characters back, and insert a ' ' in between them. What have you done so far? Does it need to be in place?
One (perhaps not optimal, but easy to follow solution) would be making a larger array, copying in alternating letters, something like (not guaranteed to work verbatim)
char foo[N]; // assuming this has N characters and you want to add a space in between all of them.
char bar[2*N];
for (int i = 0; i < N; i++) {
bar[2*i] = foo[i];
if (i != N - 1)
bar[2*i + 1] = ' ';
}
Of course, this new string is in bar, but functions as desired. At what point are you having issues?
try this
#include <stdio.h>
void add_spaces(char need_to_add[])
{
int len = strlen(need_to_add);
char with_spaces[len*2];
int space_index = 0;
for (int i=0 ; i<len ; i++)
{
with_spaces[space_index]=need_to_add[i];
with_spaces[++space_index]=' ';
space_index=space_index+1;
}
printf("%s\n", with_spaces);
}
int main()
{
char * a = "aaa";
add_spaces(a); // fraught with problems
return 1;
}

Strip numbers from a string in C

I'm looking for a simple solution for stripping numbers from a string.
Example: "GA1UXT4D9EE1" => "GAUXTDEE"
The occurrence of the numbers inside the string is erratic hence I cannot rely on functions such as scanf().
I'm new at programming in C.
Thanks for any help.
I will give you some tips:
You need to creat a new string.
Iterat over the original string.
Check if the current character is between the ascii values of numbers
If not, add it to the new string.
char stringToStrip[128];
char stripped[128];
strcpy(stringToStrip,"GA1UXT4D9EE1");
const int stringLen = strlen(stringToStrip);
int j = 0;
char currentChar;
for( int i = 0; i < stringLen; ++i ) {
currentChar = stringToStrip[i];
if ((currentChar < '0') || (currentChar > '9')) {
stripped[j++] = currentChar;
}
}
stripped[j] = '\0';
iterate through the string and check for the ascii value.
for(i = 0; i < strlen(str); i++)
{
if(str[i] >= 48 && str[i] <= 57)
{
// do something
}
}
I would agree that walking through would be an easy way to do it, but there is also an easier function to do this. You can use isdigit(). C++ documentation has an awesome example. (Don't worry, this also works in c.)
http://www.cplusplus.com/reference/cctype/isdigit/
Here is the code to do it.
int i;
int strLength = strlen(OriginalString);
int resultPosCtr = 0;
char *result = malloc(sizeof(char) * strLength);//Allocates room for string.
for(i = 0; i < strLength; i++){
if(!isdigit(OriginalString[i])){
result[resultPosCtr] = OriginalString[i];
resultPosCtr++;
}
}
result[resultPosCtr++] = '\0'; //This line adds the sentinel value A.K.A the NULL Value that marks the end of a c style string.
Everyone has it right.
Create a new char[] A.K.A. C style string.
Iterate over the original string
Check to see if the character at that iteration is a number
if not add to new string

Reverse Array of C-Strings

I have a few questions regarding array of strings in C.
I have an array char *string. I have a char *string and then I split every 4 characters in a array of strings called sep_str. So for example if char *string = 'The sum';, then char **sep_str is:
0: |_| --> "The "
1: |_| --> "Sum"
My first question is, in an array of strings in C (so array of array of chars), will there be a null terminating character at the end of each sep_str[i], or just at the last position of sep_str? Here is how I copy string into an array of strings:
for (int i = 0; i < str_length; i++) {
sep_str[i/4][i%4] = *ptr;
ptr++;
}
My second question is, how would I reverse the elements of each string in sep_str? Here's how I did it, but I feel like it is stepping out of the array of the substring. (so out of the element of the sep_str):
// Reverse each element in the array
char temp;
for (int i = 0; i < num_strs; i++) {
for (int j = 0, k = 4; j < k; j++, k--) {
temp = sep_str[i][j];
sep_str[i][j] = sep_str[i][k];
sep_str[i][k] = temp;
}
}
The copy of the strings sounds good to me. Since each string has always 4 chars, you can avoid the null terminator \0. Alternatively you need to declare sep_str as a 5x(lenght/4) matrix, to store the \0 char at the end of each string.
To reverse a string you need to iterate from the start to the middle of the string, replacing the i-th char with the length-i-1-th. You need to replace the inner for replacing k=3 to k=2.
You also need to take care of the last string, since the lenght might not be multiple of four.
char temp;
for (int i = 0; i < (num_strs - 1); i++) {
for (int j = 0, k = 3; j < k; j++, k--) {
temp = sep_str[i][j];
sep_str[i][j] = sep_str[i][k];
sep_str[i][k] = temp;
}
}
if (num_strs > 0) {
for (int j = 0, k = strlen(sep_str[i]) - 1; j < k; j++, k--) {
temp = sep_str[i][j];
sep_str[i][j] = sep_str[i][k];
sep_str[i][k] = temp;
}
}
In a C string, there will be only one termination character. But if you need to tokenize the strings, then each string must be null terminated.
But before that -
char *string = "The sum"; // should be const char* string = "The sum";
String literal in the above case resides in read only location and cannot be modified. If you need to modify, then
char string[] = "The sum";
If you don't have the terminating character in your strings then yes, you will be outside the bounds of the array since you are accessing sep_str[i][4], which is not a valid location:
sep_str[0] = 'T'
sep_str[1] = 'h'
sep_str[2] = 'e'
sep_str[3] = ' '
However, I doubt that you want to have the null character at the beginning of your string, so you need k=3 in your for loop, not k=4.
My first question is, in an array of strings in C (so array of array of chars), will there be a null terminating character at the end of each sep_str[i], or just at the last position of sep_str?
Only at the end, but if you want to treat each individual chunk as its own string, you'll need to add the \0 yourself.
My second question is, how would I reverse the elements of each string in sep_str?
You could do it with pointers...
char temp;
// Point to start of string, `str` will decay to first memory position.
char *start = str;
// Point to the end of the string. You will need to `#include <string.h>`
// for `strlen()`. Otherwise, write a `while` loop that goes until `\0` to find
// the last position.
char *end = &str[strlen(str) - 1];
// Do until we hit the middle of the string.
while (start < end) {
// Need a temp char, no parallel assignment in C.
temp = str[start];
// Swap chars.
str[start++] = str[end];
str[end--] = str[temp];
}
Assuming str is your string.

Using strcpy with a string array in C

I have a character array defined as follows: char *c[20];
I'm trying to do: strcpy(c[k], "undefined); but it's not working
I've also tried defining it as char c[20][70] with no luck.
Edit: I actually know it's an array of character arrays, I need it like that.
That's not a character array; that's an array of character pointers. Remove the * to make it a character array:
char c[20];
Then you can use strcpy:
strcpy(c, "undefined");
If you really did want an array of character arrays, you'll have to do what you said you tried:
// array that holds 20 arrays that can hold up to 70 chars each
char c[20][70];
// copy "undefined" into the third element
strcpy(c[2], "undefined");
The problem could have been you're missing the closing ", I don't know if that was a paste error though. Or, the problem could have been that you're using k without defining it, we can't know without seeing the error message you get.
If you want to set them all to that string, then just loop over them:
char c[20][70];
int i;
for (i = 0; i < 20; ++i)
strcpy(c[i], "undefined");
If what you want is to have 20 strings of 70 chars each then your second option should work:
char c[20][70];
for (int k = 0; k < 20; k++)
strcpy(c[k], "undefined");
The char *c[20] definition is incorrect because you are just defining an array of 20 pointers, and the pointers are not initialized. You could make it work in this way:
char *c[20];
for (int k = 0; k < 20; k++) {
c[k] = malloc(70);
strcpy(c[k], "undefined");
}
// then when you are done with these strings
for (int k = 0; k < 20; k++)
free(c[k]);

Resources