首页 > 解决方案 > c程序在一个框中打印问号作为输出

问题描述

有一个 char 指针变量,它的值来自一个函数。

char* apple = ....(function call)

我想按如下方式打印:

int len = strlen(apple);
for(i=0;i<len;i++){
    printf("%c ", apple[i]);
}

但是在控制台中,它会在一个框中给出一个问号作为输出。我该怎么办,我应该如何打印?谢谢。

标签: cpointerscharoutput

解决方案


我在打印部分没有看到问题,通过重新调整指向 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

推荐阅读