0

I simply make a char array str.later i made a char *p which simply pointing to it,i can access(travel ) from starting to end the str, can i manipulate the str using p, means p[i]='x'; (where i : a valid index ,x:any charater ) is valid?? actully i tried it it is working ,my question is is there no need to give it memory using malloc(i.e. p=malloc(l*sizeof(char));).

#include<stdio.h>
#include<string.h>
int main()
{
  char str[20];
  char *p;
  scanf("%s",str);
  printf("%s\n",str);
  int l=(int)strlen(str);
  // printf("l= %d\n",l);
  //p=str;
  //p=malloc(l*sizeof(char));
  p=str;
  int i;
  for(i=0;i<l;++i)
    printf("%c-",*(p+i));
  printf("\nNow p=%s\n",p);
  p[1]='x';      // it is valid , but difficult to understand?? we didnot give it memory,but it can manipulate the str as well. 
  printf("After changes made\n",p);
  printf("p=%s\n",p);   
  printf("str=%s\n",str);
  return 0;
}
harper
  • 13,345
  • 8
  • 56
  • 105
m23
  • 13
  • 2

2 Answers2

1

There is then no need to allocate memory for p in this case. The memory was allocated on the stack for str when you did: char str[20];. After you did p=str; Both p and str points to the same memory address on the stack. As long as str is in scope both str and p can be used to manipulate the value at the memory address they share. p[1]='x'; and str[1]='x'; are therefore equivalent.

Be careful though, if you keep the value of p around after str left scope and try to use it undefined behavior will ensue. The memory will be released when str leaves scope and p will point to an address on the stack that might be used by something else. Using p then might not get you what you want and making changes to p might interfere with an unrelated value.

Doing p=malloc(l*sizeof(char)); allocates new memory on the heap. Since its on the heap you are responsible for releasing this memory, it will still be allocated when processing exits the scope where it was allocated.

You can find more related content here: What is the difference between char s[] and char *s in C?

Community
  • 1
  • 1
  • 1
    No, it continued to point to the same memory location, which now might be used by something else, or garbage. – Max Oct 01 '14 at 12:54
0

Because you are only replacing the content of the byte which p points to, you dont need to alloc new memory for it.

Thallius
  • 2,482
  • 2
  • 18
  • 36
  • after assignment `p=str;` what it indicates i mean ,now they have same address, but p is now a array like str which has its own memory space or it shares it with str?? – m23 Oct 01 '14 at 11:44