So I have a program where I have user-input string (a char array), and I need to copy all of the odd indexed elements to another array using a memory-allocated pointer-to-char-array.
(the charPointer needs to be allocated to the exact amount of space required using malloc)
char charArray[16];
printf("Enter string: ");
scanf("s", charArray);
char *charPointer = malloc((sizeof(charArray) / 2 ));
char *d = charPointer;
for (char *p = charArray; *p != '\0'; p ) {
// Calculates odd-index element using bit operator
if ((p - charArray) % 2 != 0){
// Shows which elements should be copied
printf("%c", *p);
// Copy *p value to charPointer
charPointer[p-charArray] = *p;
charPointer ;
}
}
while(*d != '\0')
printf("%c\n",*d );
But I'm getting strange results, like charPointer it's only copying the first odd index and not the rest. I thought I understood pointers but this really has me puzzled. I appreciate any help!
CodePudding user response:
For starters this call
scanf("s", charArray);
^^^^
is incorrect. You need to write
scanf("s", charArray);
^^^^
This memory allocation
char *charPointer = malloc((sizeof(charArray) / 2 ));
allocates redundant memory. You should write
char *charPointer = malloc( strlen(charArray) / 2 1 );
These statements
charPointer[p-charArray] = *p;
charPointer ;
do not make a sense because they do not write sequentially characters in the dynamically pointed character array. You should write at least like
*charPointer = *p;
As the terminating zero character '\0' was not appended to the dynamically allocated array then this while loop
while(*d != '\0')
printf("%c\n",*d );
invokes undefined behavior.
Also you should to free the allocated memory.
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char charArray[16];
printf( "Enter a string: " );
scanf( "s", charArray );
char *charPointer = malloc( strlen( charArray ) / 2 1 );
char *q = charPointer;
for ( const char *p = charArray; *p != '\0'; p )
{
if ( ( p - charArray ) % 2 != 0 )
{
*q = *p;
}
}
*q = '\0';
puts( charPointer );
free( charPointer );
return 0;
}
The program output might look like
Enter a string: 012345678901234
1357913