Thanks.but I have two question-
1.Isn't the string in the main() a constant string?Why are we not getting any eror here even sfter modifying it?
2.Can you give me the sequence in which various addresses are pushed and popped out from memory?
Jerico
in the statement
char *t="hello";
the string "hello" is constant, t is a char * (pointer to char)
to make t constant you would have
const char *t="hello";
and you would get a compiler message on the call
fun(&t);
because fun() could change the value of t
program with some explaination and which prints addresses as well as the strings
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<string.h>
-
void fun(char**);
-
int main()
-
{
-
// define t as char* (pointer to char) and point it at "hello"
-
char *t="hello";
-
// print the address in t and what points at, i.e. "hello"
-
printf("t contains address %x which contains %s\n", t, t);
-
// call fun() passing the address of t
-
fun(&t);
-
// print the address in t and what points at, i.e. "hello"
-
printf("t contains address %x which contains %s\n", t, t);
-
return 0;
-
}
-
// function parameter is a pointer to char *
-
void fun(char **r)
-
{
-
// malloc storage and assign address to char* r points to
-
*r=(char*)malloc(15);
-
printf("malloc storage is at address %x \n", *r);
-
// copy "world" into storage pointed at by r
-
strcpy(*r,"world");
-
printf("*r contains address %x which contains %s\n",*r, *r);
-
}
-
-
a run gave
t contains address 404000 which contains hello
malloc storage is at address 3e5e50
*r contains address 3e5e50 which contains world
t contains address 3e5e50 which contains world