c - 变量“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;
}
解决方案
关于数组是如何存储在内存中的(数组的元素是按顺序存储的)以及字符数组是什么(即一系列以空字符结尾的字符)的观察为以下解决方案提供了直觉:
将单词数组视为一个字符序列,并'\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);
}
推荐阅读
- css - 在 vue 中对抗单页应用程序中无样式文本的闪烁
- java - 任何人都可以确认 ExpressJS 比 Spring Boot 慢吗?
- asp.net-web-api - HTTP 端点/URI 如何与它调用的 WebAPI 相关
- c - 从文件读取不会返回任何内容,但会被访问
- javafx - Javafx TilePane PrefColumns
- ruby-on-rails - 会话控制器的 Rspec
- go - 如何在错误前添加字符串?
- c# - ASP.NET Web API (.NET Core 3.1) 中的端点路由问题
- apache-kafka - 重新分配副本与分区重新分配的副本列表不匹配
- r - !is.na 删除具有 NA 值的列(在任何行中)