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

标签 arrays c memory-management char c-strings

我只需要从 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/

相关文章:

php - 如何将json数组插入mysql数据库

java - 在数组中查找其值总和等于给定总和的索引对

c++ - atol()、atof()、atoi() 函数行为,是否有稳定的方法从/到字符串/整数转换?

c++ - 跨进程内存管理

c++ - VirtualFree 是否解锁 VirtualLock?

arrays - 如何在 angular2 的 ngFor 中显示 1 个元素?

java - Android 保存和加载字符串和 boolean 值的 1D 和 2D 数组

arrays - SQL Server 查询 JSON 数组

c - execv 适用于 "/bin/ls"但不适用于 "pwd"

ios - 代表 - 保留或分配 - 释放?