【问题标题】:String pointer in C prints weird symbolC中的字符串指针打印出奇怪的符号
【发布时间】:2015-10-10 20:38:45
【问题描述】:

在 char 数组的前面动态插入一个字符后尝试打印字符串指针时遇到了一些困难。

参数 *str 是我 main 中的一个动态字符数组,而输入是单个字符,它应该在执行 insert() 后附加到动态数组的第一个元素。

int main(){ 
//code snippet. I removed other part to keep the question short
printf("How many characters do you want to input: ");
scanf("%d", &n);
str = malloc(n + 1);
printf("Input the string class: ");
scanf("%s", str);

//switch statement
case '1':
    printf("What is the character you want to insert: ");
    scanf(" %c", &input);
    insert(&str, input);
    break;
}
return 0;
}

void insert(char *str, char input) {
    char *new_str;
    int i, len = strlen(str);

    new_str = malloc(len + 1);
    new_str[0] = input;
    strncpy(&new_str[1], str, len - 1);
    new_str[len] = 0;

    for (i = 0; i < len; i++) {
        printf("%c", new_str[i]);
    }
}

当我尝试遍历 new_str 并打印出字符串数组时,它给了我奇怪的符号,我不知道它们是什么。有什么想法吗?

编辑

预期输出如下:

How many characters do you want to input: 5
Input the string:datas
The string is: datas
Do you want to 1-insert or 2-remove or 3-quit?: 1
What is the character you want to insert: a
Resulting string: adata

我得到的输出:

【问题讨论】:

  • strlen() 不计算终止空值。
  • 那我应该怎么修改呢?将 for 循环中的第二个条件更改为 new_str[i] != '\0' ?
  • strncpy() 是一个糟糕的函数,它确实做大多数人一开始想的那样。最好不要使用它,或先阅读手册。在决定不使用它之前。
  • 删除insert(&amp;str, input);中的&amp;
  • 因为&amp;str是指向字符串的指针的地址,而不是字符串本身。

标签: c string pointers ascii


【解决方案1】:

替代版本,避免任何字符串复制功能。 (因为,更改您已经知道要复制的字符串长度的 strlen(),您不再需要任何字符串函数)

char * insert_a_character(char * str, char ch)
{
char * new;
size_t len;

if (!str) return NULL;
len = strlen(str);

new = malloc (1+len+1);
if (!new) retun NULL;

new[0] = ch;
memcpy(new+1, str, len);
new[len+1] = 0;

return new;
}

【讨论】:

  • 除了使用 C++ 关键字“new”作为变量名之外,这是一个很好的答案
  • 这是故意的。 C 和 C++ 是不同的语言。混淆它们会导致更大的问题。
【解决方案2】:

如果orig需要,我假设调用者将free

char * insert(char *orig, char input) {
   char * new_str = malloc(strlen(orig) + 2); // An extra one for null
   strcpy(new_str + 1, orig);
   new_str[0] = input;
   printf("%s", new_str); // To print it out
   return new_str; // The caller needs to free this;
}

应该可以的。

【讨论】:

  • 不幸的是,它仍然打印出奇怪的符号
  • 有什么奇怪的?什么是输入?什么是原创?问题出在链上
  • ... 尝试使用调试器?
  • 除了main在哪里
  • 需要的时候我会回报的
【解决方案3】:

组装所有cmets:

void insert(char *str, char input) {
    char *new_str;
    int i, len = strlen(str);

    new_str = malloc(len + 2);
    new_str[0] = input;
    strcpy(new_str+1, str);
    new_str[len+1] = 0;

    for (i = 0; i <= len; i++) {
        printf("%c", new_str[i]);
    }
}

当然,你仍然需要对新字符串做一些事情,比如返回或释放它。

【讨论】:

  • 不幸的是,奇怪的符号仍然打印出来。
  • 那么奇怪的符号是input。拿一个调试器并检查它。我测试了它,它工作正常/
  • 但是当我注释掉其余代码并尝试从 insert() 打印输入时,它打印的是从 main() 传递的用户输入。
  • 调用函数时,必须调用为:insert(str, input);' so without the &`。
猜你喜欢
  • 2020-08-28
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 2020-05-25
  • 1970-01-01
  • 2017-07-18
相关资源
最近更新 更多