So I wrote this code:

Code:
#include <stdio.h>

char *init_str(char*s)
{
   int i;
   char init;
   for(i=0; s[i]!='\0' ; i++)
   s[i]=init;
   return s;
}
main()
{
   char *s="bla bla bla";
   printf("%s\n",init_str(s));
}


It doesn't work. The compiler doesn't detect anything, but the console crashes when I run it.
Can anyone tell me what the problem is? The init_str function in this program is supposed to initialize all values of the string to a random character.
Your string is immutable if you declare it like that, meaning you cant modify it. Instead declare it like:

char s[]="bla bla bla";

And your program should work.

Also note that depending on your compiler/crt the value of 'init' could be a null terminator so you might not get any result when printing it. You could try manually initialising init to a random character if need be.
To be a bit more precise, string literals have type const char*, so you're (wrongly) implicitly casting to char* in main. If your compiler isn't complaining about that, it's either terrible or you need to turn on more warnings.
tr1p1ea wrote:
Your string is immutable if you declare it like that, meaning you cant modify it. Instead declare it like:

char s[]="bla bla bla";

And your program should work.

Also note that depending on your compiler/crt the value of 'init' could be a null terminator so you might not get any result when printing it. You could try manually initialising init to a random character if need be.


It worked, thanks!
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement