首页 > 解决方案 > 变量“returnedstring”周围的堆栈已损坏

问题描述

我正在尝试编写一个函数,该函数将返回每个单词中最大的 ASCII 字母。

所以我的字符串是 { "hello", "and", "good", "morniny" }; 我的返回值应该是“onoy”。

我正在努力解决它并不断收到我的变量“returnedstring”已损坏的错误:

变量“returnedstring”周围的堆栈已损坏。

我在“MaxLetterToNewString”函数的最后一行收到此错误。我尝试了许多解决方法,甚至释放了这个变量。为什么我会收到此错误?

我应该怎么做才能解决它?

本来我是用函数来返回值的,但是由于它不起作用,我想在一个我称为“jr”(JustReturn)的新变量中获取值。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char MaxLetterToNewString(char *str[], int size, char *jr);

void main()
{
    char* blabla = " ";
    char* arr[] = { "hello", "and", "good", "morniny" };
    //char newarr[] = { NULL };
    char newarr;
    int size = 0;
    size = sizeof(arr) / sizeof(char*);
    //*newarr = (char*)malloc((size+1) * sizeof(char));
    newarr = MaxLetterToNewString(arr, size, *blabla);
    if (*arr == '\0')
        printf("Memory not allocated");
    else
        puts(*arr);
    free(*arr);
}

char MaxLetterToNewString(char *str[], int size,char *jr)
{
    int wordsize, letterstillnow = 0;
    char returnedstring[] = {NULL};
    char resultarr = '\0';
    for (int k = 0; k < size; k++)
    {
        wordsize = strlen(str[k]);
        for (int i = 0, j = i + 1; j < wordsize; i++, j++)
        {
            if (str[k][i] >= str[k][j])
                resultarr = str[k][i];
            else
                resultarr = str[k][j];
        }
        returnedstring[k] = resultarr;
        returnedstring[k + 1] = '\0';
    }
    jr = returnedstring;
}

标签: cmemory

解决方案


关于数组是如何存储在内存中的(数组的元素是按顺序存储的)以及字符数组是什么(即一系列以空字符结尾的字符)的观察为以下解决方案提供了直觉:

将单词数组视为一个字符序列,并'\0'作为单词之间的分隔符。扫描序列,同时检查当前单词的结尾,即'\0'字符。

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

char *MaxLetterToNewString(char **str, int size) {
    char *result = malloc((size + 1) * sizeof(*result));

    int nullCounter = 0, max = 0, i = 0;
    char c;

    while (nullCounter < size) {
        c = *(*(str + nullCounter) + i++);
        if (c == '\0') { // we reached the end of the word
            i = 0;
            ++nullCounter;
            result[nullCounter - 1] = max;
            max = 0;
        } else if (c > max)
            max = c;
    }

    result[nullCounter] = '\0';
    return result;
}

void main() {
    char* arr[] = {"hello", "and", "good", "morniny"};

    int size = sizeof(arr) / sizeof(char*);
    char *result;
    result = MaxLetterToNewString(arr, size);
    printf("%s\n", result);

    free(result);
}

推荐阅读