计算数组长度(sizeof的STR /的sizeof(char)的)将无法正常工作 [英] Calculate array length (sizeof str / sizeof (char)) won't work

查看:331
本文介绍了计算数组长度(sizeof的STR /的sizeof(char)的)将无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

功能 getStringEnd()不能正常工作,但我不知道为什么。该函数不返回字符串末尾的正确值。我已经发现,变量最大不计算正确。

不过,
INT最大= sizeof的STR /的sizeof(char)的;
应该工作,应该不会吧?

你有什么想法?

 的#include<&stdio.h中GT;
#定义MAX_FIGURES 30INT getStringEnd(为const char *海峡);INT getStringEnd(为const char *海峡)
{
    INT最大= sizeof的STR /的sizeof(字符);    INT计数器= 0;
    而(计数器< = MAX -1)
    {
        如果((STR [计数器] =='\\ 0')||(STR [计数器] =='\\ n'))返回柜台;
        计数器+ = 1;
    }
    返回0;
}INT主要(无效)
{
    CHAR数据[MAX_FIGURES]
    的for(int i = 0; I< = MAX_FIGURES - 1;我++)数字[I] ='\\ 0';    与fgets(人物,MAX_FIGURES,标准输入);    INT stringEnd = getStringEnd(安培;数字);
}


解决方案

getStringEnd()功能, STR 是一个为const char * ,没有别的。 的sizeof 运营商还给数据类型,而不是内存量的大小的按指出的变量。

您需要使用 的strlen() 获得的字符串的长度。你需要写像

  INT最大= strlen的(STR); //的sizeof(char)的== 1,固定,可以ommitted

注:FWIW,记住,的strlen()不考虑终止空

The function getStringEnd() doesn't work correctly but I don't know why. The function does not return the correct value of the string end. I already found out that the variable max is not calculated right.

But int max = sizeof str / sizeof (char); should work, shouldn't it?

Do you have any ideas?

#include <stdio.h>
#define MAX_FIGURES 30  

int getStringEnd(const char * str);

int getStringEnd(const char * str)
{
    int max = sizeof str / sizeof (char);

    int counter = 0;
    while (counter <= max -1)
    {
        if ((str[counter] == '\0') || (str[counter] == '\n')) return counter;
        counter += 1;
    }
    return 0;
}

int main(void)
{
    char figures[MAX_FIGURES];
    for (int i = 0; i <= MAX_FIGURES - 1; i++) figures[i] = '\0';

    fgets(figures, MAX_FIGURES, stdin);

    int stringEnd = getStringEnd(&figures);
}

解决方案

In getStringEnd() function, str is a const char *, nothing else. sizeof operator gives back the size of the datatype, not the amount of memory pointed by the variable.

You need to use strlen() to get the length of the string. You need to write something like

int max = strlen(str); // sizeof(char) == 1, fixed, can be ommitted

Note: FWIW, Remember, strlen() does not take into account the terminating null.

这篇关于计算数组长度(sizeof的STR /的sizeof(char)的)将无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆