在C中打印垃圾价值
我要做的是计算使用指针的字母数量和IM的数量。 一切正常,但是当我试图打印值打印的值时,我想要的 +垃圾值是因为内存的延续是
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 10000
void printChar(int *p);
int main(){
int *p,*new_p;
int c,i = 0,numOfAlNum = 0,numOfChar = 0;
p = (int*)malloc(SIZE * sizeof(int));
/*If memory cannot be allocated*/
if(p == NULL){
printf("Error! memory not allocated\n");
exit(0);
}
else
printf("Memory successfully allocated\n");
printf("enter something\n");
while((c = getchar()) != '\n'){
*(p + i) = c;
i++;
/*Add Realloc to the loop*/
new_p = realloc(p,(i+1)*sizeof(int));
/*check for ability to allocate new memory*/
if(new_p == NULL){
printf("Error! memory not allocated\n");
exit(0);
}else{
p = new_p;
}
/*Check is alphanumeric*/
if(isalnum(c)){
numOfAlNum++;
}
numOfChar++;
}
printf("The output is: \n");
for(i = 0; i < SIZE; i++){
printf("%s",(p+i));
}
printf("\nNumber of Characters is %d\n",numOfChar);
printf("Number of Alpha-Numeric is %d\n",numOfAlNum);
return 0;
}
预期输出的示例:“ Hello world” Im In是:“ Hello World&amp; ^^^ %^#” 我如何最终摆脱不必要的价值观?
what i was trying to do is to count the number of alphanumerics and im using pointers .
everything is working fine but when im trying to print the values its printing what i wanted + garbage values because of the continuation of the memory it holds
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 10000
void printChar(int *p);
int main(){
int *p,*new_p;
int c,i = 0,numOfAlNum = 0,numOfChar = 0;
p = (int*)malloc(SIZE * sizeof(int));
/*If memory cannot be allocated*/
if(p == NULL){
printf("Error! memory not allocated\n");
exit(0);
}
else
printf("Memory successfully allocated\n");
printf("enter something\n");
while((c = getchar()) != '\n'){
*(p + i) = c;
i++;
/*Add Realloc to the loop*/
new_p = realloc(p,(i+1)*sizeof(int));
/*check for ability to allocate new memory*/
if(new_p == NULL){
printf("Error! memory not allocated\n");
exit(0);
}else{
p = new_p;
}
/*Check is alphanumeric*/
if(isalnum(c)){
numOfAlNum++;
}
numOfChar++;
}
printf("The output is: \n");
for(i = 0; i < SIZE; i++){
printf("%s",(p+i));
}
printf("\nNumber of Characters is %d\n",numOfChar);
printf("Number of Alpha-Numeric is %d\n",numOfAlNum);
return 0;
}
EXAMPLE OF Expected OUTPUT : "hello world" WHAT IM GETTING IS: "hello world&^^^%^#"
how do i get rid of the unnecessary values at the end ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是打印到分配
size
的大小,打印分配的分配部分:
numofchar
。使用
“%c”
打印单个字符。“%s”
用于 strings : null字符终止字符数组。Rather than print to the size of the allocation
SIZE
,print the portion of the allocation that was assigned:
numOfChar
.Use
"%c"
to print individual characters."%s"
is for strings: null character terminated character arrays.