434 views
0 votes
0 votes

i have a doubt regarding this 
   

#include <stdio.h>
typedef struct {
    char *a;
    char *b;
    } t;
void f1 (t s);
void f2 (t *p);
main()
{
    static t s = {"A", "B"};
    printf ("%s %s\n", s.a, s.b);
    f1(s);
    printf ("%s %s\n", s.a, s.b);
    f2(&s);
}
void f1 (t s)
{
    s.a = "U";
    s.b = "V";
    printf ("%s %s\n", s.a, s.b);
    return;
}
void f2(t *p)
{
    p -> a  = "V";
    p -> b = "W";
    printf("%s %s\n", p -> a, p -> b);
    return;
}
o/p of above code is

A B 
U V 
A B 
V W


for char *s= "string":
          *(s+3)='a'; //this gives an error as i know that we can't change contetn of a string constant.
  but in above code we are replacing "A" to "v" so why there is no any problem loke above ??
code given above is from 

https://gateoverflow.in/3704/gate2004-it_61

 


 

2 Answers

Best answer
6 votes
6 votes

Yes, in C language we cannot modify a string literal as it is meant to be a constant.

A string literal is something which is not allocated a memory by the programmer so that he can modify it. For example when one uses

printf("a=%d", a);

"a=%d" is a string literal which is stored in the process address space but not in a writable region so that one could modify it. Similar is the case when one do

char *a = "hello";

Now, in the given code "A" and "B" are string literals. So, we cannot modify their contents. i.e., we cannot do

*(s.a) = 'f';

But we can do

s.a = "U";

as here we have another string literal "U" and s.a is made to point there without actually modifying "A".

edited by
2 votes
2 votes
#include <stdio.h>
int main() {
	char *var = "a_string";
	//*(var+1) = 'c'; // not allowed
	var = "another_string"; // allowed
	printf("%s\n",var );
}
O/P = another_string
  • Changing the characters of the string literal is not allowed.
  • But we can change the location pointed by the char pointer var
  • red_arrow = pointing to old string literal (  "a_string" )
  • green_arrow = pointing to new string literal (  "another_string"  ) 
edited by

Related questions

0 votes
0 votes
1 answer
1
deepak_8404 asked Oct 1, 2023
290 views
Consider a lower triangular matrix stored in row major order as p[-25 - - + 749][-25 - - - + 749] with base address = 6800, size of each element = 6 byte. Find the value ...
0 votes
0 votes
1 answer
2
jugnu1337 asked May 16, 2023
885 views
The total number of binary trees possible with height n - 2 having n nodes are?(2n - 5)^ 2n - 3 (2n - 7)^2n - 3(n - 3) ^2n - 2(2n - 7)^ 2n - 2
–4 votes
–4 votes
2 answers
4
Souvik33 asked Oct 27, 2022
647 views
*MSQ*The following figure depicts a a. A tree and only treeb. A tree with 3 nodesc. A graph (Since every tree is a graph)d. A graph and only graph