【发布时间】:2020-10-06 05:34:47
【问题描述】:
这是我的代码 sn-p:
void readandprint(){
int* num = (int*) malloc (10* sizeof(int));
for (int i =0;i<10;i++){
*(num+i) = 0;
}
char c;
while (scanf("%c",&c)==1){
if (c>='0'&&c<='9'){
*(num+c-'0')++ ; //error here
}
}
for(int j = 0;j < 10;j++){
printf("%d ",*(num+j));
}
}
然后我得到了“需要作为增量操作数的左值”错误。当我用“+=1”替换“++”时,代码工作得很好。谁能告诉我为什么?非常感谢您的任何建议。
【问题讨论】:
-
试试
(*(num+c-'0'))++;或num[c-'0']++;。 (您的问题与运算符优先级有关。) -
@IanAbbott:特别是,我认为您的第二个建议更具可读性。
-
OT: about:
int* num = (int*) malloc (10* sizeof(int));1) 在c中,返回类型为void*,可以赋值给任意指针。强制转换只会使代码混乱并且容易出错。建议去掉演员表。 2) 始终检查 (!=NULL) 返回值以确保操作成功。如果不成功 (==NULL) 则调用perror( "your error message");将您的错误消息和发生错误的文本原因输出到stderr。 -
OT:关于:
if (c>='0'&&c<='9'){更好、更清晰,并且可以处理非连续数字:#include <ctype.h>和if( isdigit( c ) )
标签: c