I am facing some problems trying to understand the difference in handling strings when they are declared as a char array and when they are declared with a pointer pointing to them. In the following code snippets, I have a few doubts.
1.While code 1 works correctly, code 2 crashes on Dev-c++ compiler.
2.Why is it that I cannot use assignments like *s = *p or *s++ = *p++ in code 2 when I have declared s and p as pointers pointing to the respective strings. And how is it valid when using s and p as arrays. in both cases dont s and p point to the first element of their respective strings? and doesnt incrementing them mean going to the next character memory location. why does the assignment not work.?

using library function, strcpy, also crashes the compiler for code 2.

code:1

#include<stdio.h>

void strc(char *s,char* p);

main()
{
      char s[] = "Anime Otaku";
      char p[] = "Bay Harbour butcher";
      strc(s,p);
      getch();
}


void strc(char *s,char *p)
{
      char *t,*x;
      t = s;
      x = p;
      printf(s);
      printf(p);
      
      while ((*s++ = *p++))
      ;
      s = t;
      p = x;
      printf(s);
}

code:2

#include<stdio.h>

void strc(char *s,char* p);

main()
{
      char *s = "Anime Otaku";
      char *p = "Bay Harbour butcher";
      strc(s,p);
      getch();
}


void strc(char *s,char *p)
{
      char *t,*x;
      t = s;
      x = p;
      printf(s);
      printf(p);
      
      while ((*s++ = *p++))
      ;
      s = t;
      p = x;
      printf(s);
}

string literals such as in your second code can not be changed because the compiler probably puts string literals in read-only memory.

The first example is making a copy of the string literal which the compiler places in read/write memory, so there is no restriction on writing to that memory location. However ... the first program still will not work correctly because there was not enough roon allocated for the first string to hold the second string.

That does make a lot of sense. Read only memory. Never thought in that direction. Thanks a lot for such a swift reply.

I have another doubt that surfaced while trying to figure this out.

1:

int *p;
      *p = 8;

2:

int *p = 8;

code:2 works while code:1 crashes.. why does that happen?

code 1 does not work because line 2 is assigning a value of 8 to some random memory location. p is a pointer that points to god only knows what.

code 2 is just initializing the pointer to address 0x00000008. Normally pointers should be initialized with 0 to indicate its a NULL pointer.

This article has been dead for over six months. Start a new discussion instead.