c++ - 在 C++ 4.8.1 中使用 strlen 的打印输出时出现段错误

标签 c++ segmentation-fault strlen

<分区>

#include<cstdio>
#include<cstring>
#include<cstdlib>

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        char *str;
        scanf("%s",str);
        int l,n,nop=1;
        l=strlen(str);
        printf("Length %d",l); //causing segmentation fault
        if(l%2==0)n=l/2;
        else n=(l-1)/2;
        for(int i=0;i<n;i++)nop=nop+abs(str[i]-str[l-1-i]);
        printf("%d\n",nop);
    }
    return 0;
}

打印字符串长度时出现错误。如果我删除该行代码有效但输出不正确。 该代码适用于 DevC++

最佳答案

您需要通过为其分配空间来初始化str:

char *str = (char *)malloc(SIZE);  

否则它将调用未定义的行为。另外,声明 lsize_t 类型,因为 strlen 返回类型为 size_t 并更改 %dprintf

中的 %zu

关于c++ - 在 C++ 4.8.1 中使用 strlen 的打印输出时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24343706/

相关文章:

c++ - 如何在 C++ 中的两个类之间定义(重载)对称二元运算符,同时考虑 r 值?

c++ - 文件无法正确读取 C++ ifstream

c++ - 如何从可执行文件中打开 bash?

c - 结构和函数的段错误

C++/Linux : Dynamic Allocation produces two different error messages

c++ - 如何写入临时文件夹

c - 在字符串数组上使用指针的段错误

c - 为什么这个计算字符串长度的 C 程序会给出错误的输出?

c - 在数组声明中使用 strlen

PHP strlen 问题