Having a weird problem while converting char pointer to char array in C/C++ . | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Having a weird problem while converting char pointer to char array in C/C++ .

For a specific need i need to split a char pointer into two char arrays The char pointer has 4 charecters and 2 char arrays should hold 2 chaecters from the pointer Like this ###################################### char * n = "1023" char a[2]; char b[2]; a[0] = n[0]; a[1] = n[1]; b[0] = n[3]; b[1] = n[4]; Now array 'a' and 'b' should hold and print the value 10 and 23 respectively but except desired output, it sometimes prints unwanted characters or some wrong value https://code.sololearn.com/cBje1CPy7Q2V/?ref=app I tried doing same thing using 'strcpy()' and storing the pointer into a bigger sized array before splitting into two smaller arrays ###################################### https://code.sololearn.com/cHSfNm2681Qh/?ref=app A help to solve this problem will be highly appreciated Thank you. NB: Question Code 1: Code without strcpy() Question Code 2: Code using strcpy()

31st Oct 2021, 3:10 PM
[B.S.] BITTU
[B.S.] BITTU - avatar
4 ответов
+ 5
you need a null ('\0') byte. #include <stdio.h> #include <string.h> int main() { char * n = "1024"; char a[3]; char b[3]; memset(a, 0, 3); memset(b, 0, 3); a[0]=n[0]; a[1]=n[1]; b[0]=n[3]; b[1]=n[4]; printf("%s\n",a); printf("%s",b); } // to get correct output: #include <stdio.h> #include <string.h> int main() { char * n = "1024"; char a[3]; char b[3]; memset(a, 0, 3); memset(b, 0, 3); a[0]=n[0]; a[1]=n[1]; b[0]=n[2]; b[1]=n[3]; printf("%s\n",a); printf("%s\n",b); }
31st Oct 2021, 3:27 PM
Flash
+ 3
Also change b[0]=n[2] and b[1]=n[3]
31st Oct 2021, 3:35 PM
Arun Ruban SJ
Arun Ruban SJ - avatar
+ 2
I would write in a much simpler way: char* n = "1024"; char a[3] = {n[0], n[1]}; char b[3] = {n[2], n[3]}; printf("%s\n",a); printf("%s",b);
31st Oct 2021, 4:36 PM
Solo
Solo - avatar
0
Thanks to Flash but instead of the 'memset()' ######################### #include <stdio.h> #include <string.h> // Check Examples //Compiler version gcc 6.3.0 int main() { char * n = "1024"; char a[3]; char b[3]; a[0]=n[0]; a[1]=n[1]; a[2]='\0'; b[0]=n[2]; b[1]=n[3]; b[2]='\0'; printf("%s\n",a); printf("%s",b); } ######################### The code Above seemed to be a better substitute
1st Nov 2021, 9:08 AM
[B.S.] BITTU
[B.S.] BITTU - avatar