【问题标题】:Assigning value to pointer correctly in C using strcpy()使用 strcpy() 在 C 中正确地为指针赋值
【发布时间】: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


【解决方案1】:

你需要Null Terminate你的字符串,就像*string_pointer = '\0';,就在你复制完字符串指针中的奇数字符之后 - 在那个循环之后,null 终止你的字符串。

How to add null terminator to char pointer, when using strcpy了解更多信息?

【讨论】:

  • 通读一下,问题就解决了。谢谢。
  • @JustinCabral 很高兴我能提供帮助。
  • @JustinCabral,您应该接受这个答案,因为它是第一个指出问题的人。我也很高兴我能帮上忙,虽然没有那么多:)
  • 是的,我确实是第一个回答的,但您的回答显示的代码 sn-p 比我的更完整。 @JustinCabral 我鼓励您接受您认为对未来读者有更多帮助的答案,即将来与您有同样问题的人! :)
  • @JustinCabral:您可以对您不接受的答案进行投票,因此两位回答者将获得相似的声誉(10 分和 15 分)。但是,未来的读者通常会首先看到接受的答案。
【解决方案2】:

在您的例程结束时,您需要空终止字符串,否则您没有字符串,您只有一个 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 = '\0'; // <-- here
//...

【讨论】:

  • 是的,这正是我需要做的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2010-09-11
  • 2019-07-10
  • 1970-01-01
  • 2010-12-19
  • 2011-10-27
  • 2015-12-16
  • 2011-01-20
相关资源
最近更新 更多