【问题标题】:string/arrays parameters help in C programming字符串/数组参数在 C 编程中的帮助
【发布时间】:2015-04-11 08:39:28
【问题描述】:

所以当我尝试打印出两个字符串时,第一个字符串不会打印出来。它 显示为空格。例如

#include <stdio.h>
#include <string.h>

int main() {
    char noun[10];   
    char temp[10];   // Stores temporary word entered by user 

    printf("Please enter word: "); 
    scanf("%s", noun); 

    temp[10] = noun[10];     
    pluralize(noun);     // Function  adds 's' to scanned word

    printf("The word changes from  %s to %s", temp, noun);

    return 0;
}

所以如果我输入“cat”,输出结果如下:

The word changes from  to cats

我需要出现原始单词,而不是空格:

The word changes from cat to cats

【问题讨论】:

  • strcpy() 看起来在这里可能会有所帮助。
  • 请分享pluralize的定义。
  • temp[10] = noun[10]; 一行中有两个越界数组访问。

标签: c string char printf scanf


【解决方案1】:

替换

 temp[10] = noun[10];      

在这里,您将名词数组的第 10 个元素复制到临时数组的第 10 个元素中,访问此位置将导致未定义的行为

strcpy(temp,noun);

【讨论】:

  • @juanchopanza 您可以通过提供正确的陈述来提供帮助。您是否阅读了整个陈述?
  • 请阅读我对问题的评论,或投票最多的答案。
  • 使用noun[10],您只能访问0 to 9。所以noun[10]out of bounds access
  • 这就是我在评论中提到的,请滚动。编译器将生成访问数组第10个位置的代码。它不会出错。
  • @ juanchopanza 我已经在评论中提到这是未定义的行为,请在此处再次为您复制“/在这里您将名词数组的第 10 个元素复制到临时数组的第 10 个元素中,访问此位置将导致未定义的行为”
【解决方案2】:

字符数组temp[] 的长度为10 个chars,从temp[0] 开始直到temp[9]。也就是说,temp[10] 超出了数组的范围,因此调用了undefined behaviour

noun[10] 也是如此。

为了将一个字符串复制到另一个,您可以使用strcpy(3)

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多