简体   繁体   English

使用指针查找字符串的长度

[英]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? 我正在尝试编写一个使用指针查找字符串长度的程序。但是无论字符串如何,我得到的结果都是1。有人可以告诉我怎么了吗?

You allocate 100 bytes ok 您分配100个字节就可以了

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 eg 'A' becomes 'B' and so on the character overflows 当该字符为!= 0时,将字符加1,例如,“ A”变为“ B”,以此类推。

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

Instead, read a string using fgets() 而是使用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
}

The %c modifier in scanf reads character sequences. scanf%c修饰符读取字符序列。 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. 您可能要使用%s修饰符。

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). 此外,当未添加长度修饰符时,返回的字符序列不会以null终止,这会使您的循环确定长度存在风险(您可能还想使用C标准库中的strlen函数,但该函数也希望返回null终止序列)。

Problem is your scanf. 问题是您的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM