#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX40 40
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
Int40 *parseString(char *str)
{
Int40 *p;
char *ptr;
int i, len, value, ptrValue;
printf("%s\n", str);
for(i = 0; i < 40; i++)
{
if(str[i] == 'a')
{
printf("%c\n", str[i]);
str[i] = '0';
printf("%c\n", str[i]);
}
}
}
int main(int argc, char *argv[])
{
// char string[40] = "
// char *str = string;
Int40 *p;
parseString("0123456789abcdef0123456789abcdef01234567");
return 0;
}
In my parseString function, between the two printf statements, I'm trying to assign the value at the specific point of 'a' to 0. I'm not sure how I'm supposed to be attempting this, and I would like to keep the variables the same as well.
Your program is having undefined behavior.
As per the standard attempting to modify a string literal results in undefined behavior because they may be stored in read-only storage or combined with other string literals.
You are passing string literal to
parseString()
function:and in
parseString()
, trying to modify it:Instead, in
main()
function you can do:which is equivalent to:
[Note the terminating null-character at the end.]
So, you can do:
Note that in my program, I am only demonstrating the replacement of
'a'
with'0'
character. Hence, I removedtypedef struct Int40...
which exists in OP's code.Your problem here is that you are passing to
parseString
a pointer to a string literal. Modifying the contents of string literals is undefined behaviour and most of the times string literals reside in read only memory, that's why your program crashes.You have to create an array and initialize it with the string you want, then pass that array to the function:
Bear in mind when you pass an array to a function, the function gets only a pointer to the first element of the array. For that reason the function being called cannot determine the length of the array. It's better practice to pass the length of the array as well. That's why I added
size_t len
as an argument inparseString
. Inmain
where thearray
is declared, I calculate the length of the array withsizeof text / size *text
. Note that this only works with pure array, if you didsizeof str / sizeof *str
inparseString
, you will definitively get a wrong result, that's why you should always pass the length of the array.