c - c程序在一个框中打印问号作为输出
问题描述
有一个 char 指针变量,它的值来自一个函数。
char* apple = ....(function call)
我想按如下方式打印:
int len = strlen(apple);
for(i=0;i<len;i++){
printf("%c ", apple[i]);
}
但是在控制台中,它会在一个框中给出一个问号作为输出。我该怎么办,我应该如何打印?谢谢。
解决方案
我在打印部分没有看到问题,通过重新调整指向 char 数组的指针的功能需要进行调查。
// In this example, getString function returns string literal
// That is being iterated in the next for loop over its length and prints its characters
#include <stdio.h>
#include <stdlib.h>
char *getString(void); // declare
int main() {
char *apple = getString();
int len = strlen(apple);
for(int i = 0; i < len ; i++) {
printf("%c ", apple[i]);
}
return 0;
}
char *getString() {
return "somesthing";
}
下面的示例将仅打印可打印的 ascii 字符。从 0 到 31 ,0 代表空值,1 代表 SOH,依此类推。如果您预期打印奇怪的输出,您将无法打印控制代码(ASCII 代码 < 32)。
#include <stdio.h>
#include <string.h>
#define PRINTABLE_ASCII_CHAR_COUNT 96
/*
Printable chars list
"! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~"
*/
char *getASCIIs(void);
int main() {
char *apple = getASCIIs();
int len = strlen(apple);
for(int i = 0; i < len ; i++) {
// p << i << ((i % 16 == 15) ? '\n' : ' ');
printf("%c ", apple[i]);
}
return 0;
}
char *getASCIIs() {
static char buffer[PRINTABLE_ASCII_CHAR_COUNT];
for (int i = 32, j=0 ; i <= PRINTABLE_ASCII_CHAR_COUNT; i++, j++) {
buffer[j] = i;
}
return buffer;
}
enter code here
推荐阅读
- javascript - 用于从 api 获取 json 数据的 url 格式
- php - Wordpress 多站点链接已损坏
- html - 角度或html如何按条件显示模板
- r - 如何让 tinytex 在 rstudio 上生成 pdf?
- ios - 在嵌套对象上使用 for 循环
- javascript - Stack Navigator 抽屉图标单击抽屉未打开但滑动打开时
- javascript - 如何在 React Native 中集成 QuickBlox?
- javascript - JavaScript - 解析 json 对象时遇到问题
- c# - 在 Linq 中创建对象的新实例
- java - 尝试异步引导 Hibernate 时出现 Spring Boot 2.1.0 错误