【发布时间】:2014-01-26 17:10:02
【问题描述】:
我在Cplusplus做一个教程
有这个例子:
/* scanf example */
#include <stdio.h>
int main ()
{
char str [80];
int i;
printf ("Enter your family name: ");
scanf ("%79s",str);
printf ("Enter your age: ");
scanf ("%d",&i);
printf ("Mr. %s , %d years old.\n",str,i);
printf ("Enter a hexadecimal number: ");
scanf ("%x",&i);
printf ("You have entered %#x (%d).\n",i,i);
return 0;
}
我在我的 Macbook 上尝试过,当我执行“制作示例”时出现此错误;
example.c: In function ‘main’:
example.c:25: warning: format ‘%79s’ expects type ‘char *’, but argument 2 has type ‘char (*)[80]’
当我执行“valgrind ./example”时,我会收到此消息;
==1326== Memcheck, a memory error detector
==1326== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==1326== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==1326== Command: ./example
==1326==
--1326-- ./example:
--1326-- dSYM directory is missing; consider using --dsymutil=yes
Enter your family name: Park
Enter your age: 20
Mr. Park, 20 years old.
==1326==
==1326== HEAP SUMMARY:
==1326== in use at exit: 8,280 bytes in 3 blocks
==1326== total heap usage: 3 allocs, 0 frees, 8,280 bytes allocated
==1326==
==1326== LEAK SUMMARY:
==1326== definitely lost: 0 bytes in 0 blocks
==1326== indirectly lost: 0 bytes in 0 blocks
==1326== possibly lost: 0 bytes in 0 blocks
==1326== still reachable: 8,280 bytes in 3 blocks
==1326== suppressed: 0 bytes in 0 blocks
==1326== Rerun with --leak-check=full to see details of leaked memory
==1326==
==1326== For counts of detected and suppressed errors, rerun with: -v
==1326== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
问题 1。 “make example”给出了一个错误,但程序做了它应该做的事情。 那么这里的错误是什么?
问题 2 我做了很少的研究,我了解到你不能在 C 中分配一个 char,因为 char 是不可变的。这就是 char 与 int、float 或 double 的不同之处。如果是这样,我怎么能在这里分配 str ?
问题 3 什么是 Char 数组?我读了几篇文章,但我不明白它是如何工作的!!!
char str [80];
意味着 str 最多可以占用 80 个字节,对吗? 那是什么
scanf ("%79s",str);
?
非常感谢你们的帮助,祝 2014 年快乐! :)
【问题讨论】:
-
ad 1) 这是一个警告,而不是错误。我认为该消息非常明确地说明了它的警告内容,即
str的类型是字符数组,而指针是预期的。 -
声明
i为unsigned int i; -
鉴于警告,您确定您之前在
scanf调用中没有&str吗?你看,&str的类型是char (*)[80],但str是完全正确的,不应该给你警告。
标签: c char variable-assignment arrays