【发布时间】:2017-01-08 15:36:46
【问题描述】:
我已经尝试解决这个练习一周了,但我的代码不起作用,我不明白为什么以及如何更改它。练习是: 从用户那里接收一个长度,然后接收一个字符串(str)只要'length',然后从用户那里接收一个数字(int n)。然后我需要执行函数'void ReverseNumWords(char * str,int n ). 该函数反转字符串中的前 n 个单词。例如:对于“我是你的父亲星球大战”和 n=3: '你是我的父亲星球大战'。假设单词用“ ”分隔是正确的。谢谢您的帮助!!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
void Reverse()
{
int len,num;
char *str;
printf("Please enter how many chars to allocate:\n");
//Asking from the user the length of a string.
scanf("%d", &len);
//Allocating memory for the string.
str = (char*)calloc(len, sizeof(int));
//Making sure the allocation was successful.
if (!str)
printf("Error: Cannot allocate Memory\n");
printf("Allocated %d chars\n", len);
printf("Please enter your string:\n");
scanf("%s", str);
printf("Please enter how many words to reverse:\n");
scanf("%d", &num);
ReverseNumWords(*str, num, len);
free(str);
}
void ReverseNumWords(char*str, int num,int len)
{
char *sub;
char temp;
//Allocating memory for the string.
sub = (char*)calloc(len, sizeof(int));
//Making sure the allocation was successful.
if (!sub)
printf("Error: Cannot allocate Memory\n");
int i, j,l;
i = j = 0;
for (; i < len, j <= num; i++)
if (str[i] == '\0' || str[i] == 0)
j++;
for (l = 0; l < i; l++)
sub[i] = str[i];
for (j = 0; j < i; j++)
temp = sub[j];
sub[j] = sub[i - (1+j)];
sub[i - (1+j)] = sub[j];
reverseWords(*sub);
}
void reverseWords(char *sub)
{
char *word_begin = sub;
char *temp = sub;
while (*temp)
{
temp++;
if (*temp == '\0')
{
reverse(word_begin, temp - 1);
}
else if (*temp == ' ')
{
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
reverse(sub, temp - 1);
}
void reverse(char *begin, char*sub, char *end)
{
char temp;
while (begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
printf("%s\n", sub);
}
【问题讨论】:
-
首先,为什么要使用 sizeof(int) 来分配字符?
-
你是对的!改变了它,代码仍然不起作用......我觉得有一个简单的方法来编码这个,而不是我让它变得更复杂......任何提示?你能告诉我你会怎么做才能成功解决它吗?
-
我现在正在处理您的代码。我的第一件事是改变你阅读它的方式,我会尝试阅读字符,而不是字符串。请等一下
-
出现段错误,我正在尝试找出原因
-
在 VisualStudio 前花了几个小时,无法弄清楚为什么代码不起作用......
标签: c string pointers malloc calloc