我只需要从 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
输入字符串:测试
复制 etn
但打印 etng
。
我不明白为什么对于某些字符串,它会在末尾打印出额外的字符,而我什至从未复制过该值。
最佳答案
在复制完字符串指针中的奇数字符后,您需要空终止字符串,例如*string_pointer = '\0';
-在该循环之后,以 null 终止您的字符串。
了解更多信息How to add null terminator to char pointer, when using strcpy ?
关于arrays - 使用 strcpy() 在 C 中正确为指针赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63998941/