0
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *str=malloc(sizeof(char)*100);
    int length=0;
    printf("Enter string :\n");
    scanf("%c",str);
    while(*str)
    {
        length++;
        *str++;
    }
    printf("%d",length);
    return 0;
}

I'm trying to write a program to find length of string using pointers.But whatever the string, I'm getting the result as 1. Can somebody tell me what's wrong?

adrtam
  • 6,991
  • 2
  • 12
  • 27
Combospirit
  • 313
  • 1
  • 2
  • 11

3 Answers3

2

You allocate 100 bytes ok

char *str=malloc(sizeof(char)*100);

int length=0;
printf("Enter string :\n");

You have a string but read one character

scanf("%c",str);

While that character is != 0 You increment the character with one e.g. 'A' becomes 'B' and so on the character overflows

while(*str)
{
    length++;
    *str++;

Instead, read a string using fgets()

const int maxlen = 100;
char *str=malloc(maxlen); 

if (fgets(str,maxlen,stdin) != NULL)
{
  // now to calculate the length
  int length = 0;
  char* p = str;  // use a temp ptr so you can free str 
  while (*p++) 
  { 
    ++length; 
  }
  printf("length=%d", length);
  free(str); // to avoid memory leak
}
AndersK
  • 35,813
  • 6
  • 60
  • 86
1

The %c modifier in scanf reads character sequences. As you did not provide a field width, it reads by default only one character per time. You might want to use the %s modifier.

Further, when no length modifier is added, the returned character sequence is not null terminated, which makes your loop to determine the length risky (you also might want to use the strlen function from the C standard library, but this function also expects a null terminated sequence).

Pim
  • 135
  • 1
  • 2
  • 13
0

Problem is your scanf.

char *str=(char*)malloc(sizeof(char)*100);

printf("Enter string :\n");
scanf("%s",str);
int i = 0;
for (i = 0; i < 100 && str[i] != '\0'; i ++)
{
}
printf("%d",i);
chris01
  • 10,921
  • 9
  • 54
  • 93
  • [Don't cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). And add a length-modifier to the format so the buffer won't be overrun. And always check what `scanf` returns. – Some programmer dude Feb 28 '19 at 18:19
  • If I do not cast the malloc some compiles would give me an error. I tried with GCC 8.2. I did not try to optimize OPs code, just make it run. But you are generally right - C and memory needs some attention to be safe. – chris01 Feb 28 '19 at 18:33
  • 1
    Then you're using C++ and not C. – Some programmer dude Feb 28 '19 at 18:38