edited by
517 views
2 votes
2 votes
# include<stdio.h>
int main() {
    char g1[7] = “4567”, *q;
    q = g1 + 1;
    *q = ‘0’;
    printf(“%s”, g1);
}
---------------------------------------------

i really getting confused.i thought that it will produce error because of *q = ‘0’;but it is printing 4067.

how will i get to know that it is allowed or not.?because here string is getting modified.

is g1[1]='a' allowed here.

can someone please clarify this ?
edited by

1 Answer

Best answer
2 votes
2 votes
# include<stdio.h>
int main() {
    char g1[7] = “4567”, *q;
    q = g1 + 1;
    *q = ‘0’;
    printf(“%s”, g1);
}
  • In this program g1[] array is available in the stack. And hence modifiable (Write allowed)
  • q is just a helper pointer.

One example to your doubt:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
	char *old1 = "helloworld1";
	char old2[] = "helloworld2";

	char *dst1 = old1 + 5;
	char *dst2 = old2 + 5;
	
	char *src = "windows";

	//strcpy(dst1,src);  // DOES NOT WORK
	strcpy(dst2,src);

	printf("old1 = %s\n",old1);
	printf("old2 = %s\n",old2);


	return 0;
}


O/P:
old1 = helloworld1
old2 = hellowindows
  • using old2[] makes the string literal modifiable because it is in the stack.
  • But using the character pointer only string literal stored in read-only area of memory, which becomes nonmodifiable.
  • strcpy working
edited by

Related questions

0 votes
0 votes
0 answers
1
Anirudh Kaushal asked Apr 6, 2022
191 views
#include<stdio.h struct marks { int p:3; int c:3; int m:2; }; void main() { struct marks s = {2, -6, 5}; printf("%d %d %d", s.p, s.c, s.m); }What does p:3 means here ?
0 votes
0 votes
1 answer
2
Parshu gate asked Nov 19, 2017
359 views
#include<stdio.h>int main(){ int a=2;if(a==2){ a=~a+2<<1; printf("%d",a);}}
2 votes
2 votes
2 answers
3
Parshu gate asked Nov 5, 2017
1,293 views
OPTIONSA)7,19 B) 10,1 C) 10,23 D)10,32
1 votes
1 votes
1 answer
4
Archies09 asked Apr 23, 2017
3,179 views
What will be the output of the program?#include<stdio.h int addmult(int ii, int jj) { int kk, ll; kk = ii + jj; ll = ii * jj; return (kk, ll); } int main() { int i=3, j=4...