Regarding null character

closed account (4ET0pfjN)
Hi, I want to clarify, for the program I have written, is the reason var 'third' doesn't output to screen is b/c the null terminator overwrote the first character in the array from var 'third'

Here is my code:
=================
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdlib.h>//in C++, this would've been cstdlib (NO .h)
#include <stdio.h>//in C++, this would've been cstdio (NO .h)
#include <string.h>//in C++, this would've been string (NO .h) I think

char first[] = "=First=";
 char second[] = "=Second=";
 char third[] = "=Last=";

 int main() {

 printf("%s\n%s\n%s\n",first,second,third);//EXPECTED: =First= \n =Second= \n =Last= \n
 printf("\n");

 strcpy(second,"012345678");//var second[] now holds: 012345678
 printf("%s\n%s\n%s\n",first,second,third);//EXPECTED: =First= \n 012345678 \n =Last= \n
 //	WRONG EXPECTED: b/c of null character in 012345678'\0' that overwrote first char in var third

 strncpy(second,"012345678", sizeof(second));
 printf("%s\n%s\n%s\n",first,second,third);
 
 printf("%s",third);//NB: it's gone now...
 
 return 0;
	
 }


So what I mean is: var 'second' is [=][S][e][c][o][n][d][=][\0] and when I call strcpy
of '012345678', it's length is 10 characters as oppose to 9 characters in '=Second=', and since this is static array, the null character in '012345678' is forced to occupy
the next space during the printf, so it takes up the first space in var 'third' which makes it unusable var (var 'third' i mean).

BTW: this is C, not C++, but should be simiilar...

Any help appreciated.
Last edited on
Yes, you are correct, you can verify this by re-ordering the declaration of your variables and check out the side effects.
By the way you should know that standard C headers are written in C++ without extension and with "c" prefix. So the following your comment for the #include

#include <string.h>//in C++, this would've been string (NO .h) I think

is incorrect.

C - <string.h>, C++ - <cstring>
right. <string> and <cstring> are 2 different headers.

<string> has the std::string class
<cstring> has strlen, strcpy, etc c-string functions.
Topic archived. No new replies allowed.