【发布时间】:2021-01-07 22:36:47
【问题描述】:
我只需要从 char 数组中取出奇数值,然后使用指针将它们复制到大小正确的动态内存中。
但是,当运行我的程序时,它适用于某些输入字符串而不适用于其他输入字符串。有什么我做错了吗?我似乎无法弄清楚发生了什么。
/* A.) Include the necessary headers in our program */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STRING_LENGTH 32
int main() {
/* B.) Declare char array with inital size of 32 */
char input_string[MAX_STRING_LENGTH];
/* C.) Recieve user input.
Can save the first 31 characters in the array with 32nd reserved for '\0' */
printf("Enter a string of characters: ");
/* D.) Using the technique we discussed to limit the string to 31 charaters */
scanf("%31s", input_string);
printf("\n");
/* Will be used to determine the exact amount of dynamic memory that will be allocated later */
int odd_value_count = 0;
printf("Odd Characters: ");
for(int i = 0; i < strlen(input_string); i++) {
if(i % 2 != 0) {
printf("%c ", input_string[i]);
odd_value_count++;
}
}
printf("\n");
printf("Odd value count: %d\n", odd_value_count);
/* E.) Delecaring the pointer that will hold some part of the input_string
Pointer will be a char type */
char *string_pointer;
/* G.) Allocating the space before the copy using our odd value count */
/* H.) The exact amount of space needed is the sizeof(char) * the odd value count + 1 */
string_pointer = (char *)malloc(sizeof(char) * (odd_value_count + 1));
if (string_pointer == NULL) {
printf("Error! Did not allocte memory on heap.");
exit(0);
}
/* F.) Copying all charcters that are on the odd index of the input_string[] array
to the memory space pointed by the pointer we delcared */
printf("COPIED: ");
for (int i = 0; i < strlen(input_string); ++i) {
if(i % 2 != 0) {
strcpy(string_pointer++, &input_string[i]);
printf("%c ", input_string[i]);
}
}
/* Printing out the string uses the pointer, however we must subtract odd_value_count to
position the pointer back at the original start address */
printf("\n%s\n", string_pointer - odd_value_count);
return 0;
}
这个输入字符串:01030507
工作正常,复制和打印:1357
输入字符串:testing
复制etn,但打印etng。
我不明白为什么对于某些字符串,它会在最后打印出多余的字符,而我什至从不复制值。
【问题讨论】:
-
“我似乎无法弄清楚发生了什么”——您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定在哪个点您的程序停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?。
-
如果不是我自己调试,我就不会在这里发帖。关键是在调试之后我不明白想要继续。不过还是谢谢。
标签: arrays c memory-management char c-strings