Combospirit
Combospirit

Reputation: 313

Finding length of string using pointers

#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?

Upvotes: 0

Views: 856

Answers (3)

AndersK
AndersK

Reputation: 36092

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
}

Upvotes: 2

Pim
Pim

Reputation: 135

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).

Upvotes: 1

chris01
chris01

Reputation: 12431

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);

Upvotes: 0

Related Questions