Reputation: 35
I am new to pointers, please let me know how can i print the entered character.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = malloc(32 * sizeof(char));
*ptr = 'h';
ptr++;
*ptr = 'e';
ptr++;
*ptr = 'l';
ptr++;
*ptr = 'l';
ptr++;
*ptr = 'o';
ptr++;
*ptr = '\n';
printf("value entered is %s\n", ptr);
return 0;
}
I want to print hello
Upvotes: 2
Views: 61
Reputation: 1251
You can, rather using the malloc()
function, use the calloc()
function, which achieves the same goal of malloc()
, but fills the memory with '\0'. This makes it easier to play with non-fixed length strings.
You can find the documentation of this function here.
Here is the code I've made :
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = calloc(32,sizeof(char));
*ptr = 'h';
ptr++;
*ptr = 'e';
ptr++;
*ptr = 'l';
ptr++;
*ptr = 'l';
ptr++;
*ptr = 'o';
ptr++;
*ptr = '\0'; //It should be null terminated
ptr -= 5;
printf("value entered is %s\n", ptr);
free(ptr);
return 0;
}
Upvotes: 0
Reputation: 213842
You should fix your code like this, with a temporary pointer:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char* ptr;
ptr = malloc(32 * sizeof(char));
if(ptr == NULL)
{
puts("Allocation failed");
return EXIT_FAILURE;
}
char* tmp = ptr;
*tmp = 'h';
tmp++;
*tmp = 'e';
tmp++;
*tmp = 'l';
tmp++;
*tmp = 'l';
tmp++;
*tmp = 'o';
tmp++;
*tmp = '\0'; // NOTE: null termination not \n
printf("value entered is %s\n", ptr);
free(ptr);
return 0;
}
A proper version without messy pointer arithmetic looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char* ptr;
ptr = malloc(32 * sizeof(char));
if(ptr == NULL)
{
puts("Allocation failed");
return EXIT_FAILURE;
}
strcpy(ptr, "hello");
printf("value entered is %s\n", ptr);
free(ptr);
return 0;
}
Upvotes: 4
Reputation: 16876
You forgot the null-terminator. Add this:
ptr++;
*ptr = '\0';
Also, the pointer is now pointing to the null-terminator (or previously the newline character). You have to set it back to point to the 'h'
again:
ptr -= 6;
And when you're done, you should free the memory:
free(ptr);
Upvotes: 5