char* test(constchar *str)
{
char *chr1 = NULL;
for (int i = 0; i <= strlen(str); i++)
{
if (blah_blah)
{
// here
chr1[i] = str[i]; // acces violation writing location
}
}
return chr1;
}
After some elements of str1 are chosen by blah_blah in "here", I want to set those chosen elements to chr1 and return it but I get errors
1-If I do like that, I am getting an access violation
2-If I do not set chr1 to null, I got "Uninitialized variable "chr1" used"
What Should I do?
NOTE: I want the code to be compatible with c. That is the reason why I used Char arrays and not strings
Now recall array access / pointer dereferencing syntaxes:
1 2 3
chr1[ foo ] = 'x';
// is same as
*(chr1 + foo) = 'x';
Lets insert the actual values of my example: *( NULL + 42 ) = 'x';
We try to write to a char object that is at memory address NULL + 42.
When did we reserve the memory address NULL + 42 for a char? NEVER
The chr1 is a pointer. Pointer points to some allocated memory.
You never did allocate any memory for your characters and you never made the chr1 to point to such memory.
You have to allocate memory for your data. If you want to write C, then allocate as one does in C.
char* test(constchar *str)
{
/* Determine the length of str, including null character room. */
int len = strlen(str) + 1;
/* Allocate storage dynamically */
char *chr1 = (char*)malloc(len * sizeof(char));
for (int i = 0; i < strlen(str); i++)
{
if (blah_blah)
{
/* Copy a character frm str to char1 and increase pointer */
*chr1++ = str[i];
}
}
/* A string end with null character.
(chr1 can shorter than str.) */
*chr1 = '\0';
return chr1;
}
note that the above example quietly fixes the code or changes the logic.
did you want to filter (make chr shorter than str due to removal of some letters) or replace (same length but different values for some letters) ??
if you want to filter, he did it for you by increment of the pointer, that tracks the 2 indices distinctly and correctly. Doing it as per the original, both strings [i], is a bug.
*chr1++ = str[i]; is critical to the logic.
He didnt say anything about that fix, so I wanted to elaborate.