使用 strcpy() 在 C 中正确地为指针赋值

Assigning value to pointer correctly in C using strcpy()

我只需要从 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 '[=10=]' */
    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.

我不明白为什么对于某些字符串,它会在末尾打印出额外的字符,而我什至从未复制过值。

您需要 Null 终止 您的字符串,就像这样 *string_pointer = '[=10=]';,就在您完成复制字符串指针中的奇数字符之后 - 在该循环之后,null终止你的字符串。

阅读更多内容?

在你的例程结束时,你需要用 null 终止字符串,否则你没有字符串你只有一个 char 数组,你可以使用 string_pointer 已经指向一个过去您要保存的字符串的末尾:

//...
for (int i = 0; i < strlen(input_string); ++i) {

    if(i % 2 != 0) {
        strcpy(string_pointer++, &input_string[i]);
        //as you are copying characters, you can do this:
        //*string_pointer++ = input_string[i]; 
        //instead of strcpy
        printf("%c ", input_string[i]);
    }
}
*string_pointer = '[=10=]'; // <-- here
//...