I'm trying to create a program that displays the string length of an entered string with a pointer to aforementioned string. When I input a string without spaces, the length is correct. When I enter a string with spaces, the length is incorrect. Please describe my mistake and recommend ways to fix it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int l,n;
char s[n], *p=s;
*p = malloc(sizeof(char)*5);
n = sizeof(*p);
if (p==NULL)
printf("Unable to allocate memory");
printf("Input a string: ");
scanf("%s", p);
l = strlen(p);
printf("\nLength of given string: %d\n", l);
}
Input:
Input a string: June 27
Output:
Length of given string: 4
pwith a length of5. You're overflowing your buffer.char s[n];,*p = malloc(sizeof(char)*5);Each of those should be generating at least a warning, which you shouldn't ignore. Either that, or what you posted is not the real code.scanf("%s"...reads to the first whitespace, and you are responsible for providing the memory, so it's a good thing you put a space after "June".