使用指针算术编码字符串长度函数

标签 c string pointers string-length

我正在初级 CS 类(class)中学习 C,我们的任务是编写一个仅使用字符串指针查找字符串长度的函数。我有以下代码:

#include <stdio.h>

int strlength(char* str);

int main() {
    char *str;
    int comp;

    printf("Please enter the string: ");
    scanf("%s", str);

    printf("The length of the string is: %d\n", strlength(str));
    return 0;
}

int strlength(char *str) {
    int length = 0;

    while(*str != '\0') {
        length++;
        str++;
    }
    return length;
}

我不太确定哪里出现了段错误。我尝试在 strlength 函数中创建第二个指针,该指针等于 str 并递增该指针,但这也给我带来了段错误。任何见解将不胜感激!

最佳答案

char *str;
int comp;

printf("Please enter the string: ");
scanf("%s", str);

您应该在 scanf 之前在堆中为 *str 分配内存(使用 malloc )。如果您不想使用 malloc,请将其更改为 char[number],这样它就可以在堆栈而不是堆中分配内存

关于使用指针算术编码字符串长度函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356380/

相关文章:

c - 使用 ffmpeg 和 sdl2 进行口吃渲染

c - 使用 Blowfish 加密和解密消息

javascript - 如果存在,则在字符第 3 次出现后替换所有内容

python - 使用python替换两个子字符串之间的字符串

python - 使用 Python 的 ctypes 传递/读取声明为 "struct_name *** param_name"的参数?

C 字符数组在传递给函数后损坏

c - while 循环继续不中断

r - 在第一个分号之前提取字符串的一部分

c - 使用双指针和 malloc 函数的二维数组

c - 指向 C 中二维数组的指针