首页 > 解决方案 > 从数组中获取单个元素?

问题描述

我正在尝试一次打印一个char数组s。该程序我打印了数组中定义的索引之后的所有字母。

我面临的问题是用户插入短语然后分配它。如何使用指针从字符串中调用字母?

你能用它strtok来分割这个字符串吗,我试着把它设置delim为“”没有输出。换句话说,让它像 Python 一样成为一个列表split()

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>


int main() {
        
    char *s;
    s = malloc(1024 * sizeof(char));
    scanf("%[^\n]", s);
    s = realloc(s, strlen(s) + 1);
   
    //printf("%s \n", s);
        
    for (int i = 0 ; i <strlen(s); i++){
        printf("%s \n", &s[i]);        
    }
        
    return 0;
}

标签: c

解决方案


printf("%c\n", s[i]);

或者

printf("%c\n", *(s + i));

推荐阅读