I am trying to understand what is wrong with my code and my understanding of pointers, arrays and string in C.
I tried to create an array of strings, to be able to loop over it and to test any functions that take a string as a parameter.
In this case, i'm trying to check my private implantation of memset
called Memset
.
This is my code:
#include <stdio.h>
#include <string.h>
/*First Try, did not work: */
/*const char * strings_array[] = {*/
/* "First string",*/
/* "213123Second_string3",*/
/* "",*/
/* "-3",*/
/* "s",*/
/*};*/
/* Second try, also does not work: */
const char **strings_array = (char *[]){"a", "b", "c"};
int main ()
{
while(*strings_array)
{
char *string = strings_array;
printf( "Before Memset, target is \"%s\"\n", *string );
if (NULL == Memset(*string, '$', 4))
{
fprintf(stderr,"Memset failed!\n");
}
printf( "After Memset, target is \"%s\"\n\n", *string );
++strings_array;
}
return (0);
}
I know that a string
in C is not a type
but a char *
.
But it is also a string literal
, which means I can't change it, and can only read it.
That's why it's not working?
Because I'm passing it to Memset
and Memset
tries to change it while it can not be changed because it's a string literal?
This is my implantation of my Memset
function:
void *Memset(void *str, int c, size_t n)
{
unsigned char *string = str;
if (NULL == str)
{
return (NULL);
}
while(n > 0)
{
*string++ = (unsigned char) c;
--n;
}
return (str);
}