c - 为什么我的函数不返回空指针?

标签 c parsing pointers stm32 strtok

我的可视代码有问题,在在线编译器上一切正常,但在 stm32 nucleo 上尝试时它不返回 NULL,问题出在哪里?它不能中断 while 循环。

#include <string.h>
#include <stdio.h> 
#include <stdlib.h>
#include <math.h>
#include <ctype.h>

int funk(char *skai) {
    char delim[] = "+-=";
    int i = 0;
    float x, d = 0;
    char *array[2];
    char *ptr = strtok(skai, delim);
    while (ptr != NULL) {
        array[i++] = ptr;
        ptr = strtok(NULL, delim); // <---- doesnt return null, endless loop
    }
    int a = atoi(array[0]);
    float b = atof(array[1]);
    int c = atoi(array[2]);
    if (c != 0) {
        d = b * b - 4 * a * c;
        if (d > 0) {
            float root1 = (-b + sqrt(d)) / (2 * a);
            float root2 = (-b - sqrt(d)) / (2 * a);
            if (root1 > root2) {
                x = root1;
            } else {
                x = root2;
            }
        } else {
            x = -b / (2 * a);
        }
    } else {
        x = b / a;
    } //printf("%0.3f\n", x);
    return x;
}

int main(void) {
    char rxd[20] = "2x^2+x/5+2=0";
    funk(rxd);
}

最佳答案

给定 skai 指向包含“2x+2=0”的 char 数组,对 strtok 的一系列调用带有分隔符“+-=” 应该首先返回指向“2x”(的第一个字符)的指针,然后是“2”,然后是“0”,最后是一个空指针。编写的代码尝试将这些值存储在 array[0]array[1]array[2] 中。但是,array 没有元素 2,因为它只定义了两个元素。所以程序溢出数组,程序的结果行为不是由 C 标准定义的。可能是程序随后以导致 strtok 行为异常的方式覆盖内存。

array的定义变大,在调用strtok的循环内,监控i的值:如果达到数组大小的限制,打印错误消息并终止函数(或整个程序)。

关于c - 为什么我的函数不返回空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60756974/

相关文章:

c - 互斥访问和系统调用

c - webkit加载注入(inject)图片内容

c - 使用 scanf 解析 hh :mm:ss, 一些输入出现奇怪的错误

c++ - 为什么这个数组的第 0 个索引仍然不等于 0?

c++ - SDL 为什么在堆上而不是堆栈上创建纹理

C加法使用模数

c++ - 核心转储的监控应用程序

c++ - GLL Parser Combinator or Generator in/for C or C++

parsing - 在 ANTLR 中,是否有表示一组规则的所有排列的交替的快捷符号?

pointers - 将实现特征的数据存储在向量中