使用 C 从字符串数组中获取特定字符
get a specific char from array of strings with C
我有一个字符串数组,我想从以下位置打印特定字符:
char *Code[17]={"MAIN: add r3, LIST",
"LOOP: prn #48",
"lea STR, r6",
"inc r6",
"mov r3, K",
"sub r1, r4",
"bne END",
"cmp val1, #-6",
"bne %END",
"dec K",
"jmp %LOOP",
"END: stop",
"STR: .string “abcd”",
"LIST: .data 6, -9",
".data -100",
".entry K",
"K: .data 31"};
printf("%s",&Code[1][4]);
我要打印的字符是来自第二个字符串的“:”(循环:prn #48)。
当我尝试使用 printf("%s",&Code[1][4]); 打印时,我得到的是 ": prn # 48
我想单独打印字符“:”,所以我也尝试使用 %c 进行打印并收到此警告:
warning: format '%c' expects argument of type 'int', but argument 2 has type 'char *'
如何从数组中的特定字符串中获取特定字符?
另外,为什么我会收到 %c 需要 int 类型的警告? %c 不是用来打印和扫描 A 字符的吗?
printf("%s",&Code[1][4]);
打印从 &Code[1][4]
开始的 C 字符串。
printf("%c",Code[1][4]);
打印字符 Code[1][4]
(来自地址 &Code[1][4]
,但这与 %c
无关,字符需要传递,而不是其地址) .
您尝试打印一个指针值而不是字符。
printf("%s",&Code[1][4]); // print a string starting at ':'
printf("%c",&Code[1][4]); // try to print address of char
printf("%c",Code[1][4]); // Print the char you want
用于输出字符的转换说明符 c
需要类型 int
的标量参数(在 char
类型的参数表达式整数提升为类型之后int
) 被函数转换为类型 unsigned char
并输出。
然而这个表达式
&Code[1][4]
具有类型 char *
而不是 char
。
另一方面,转换说明符 s
用于输出字符串而不是单个字符(尽管使用此说明符您可以输出单个字符,如下所示)。
所以你需要的是以下内容
printf( "%c", Code[1][4] );
您可以使用转换说明符 s
和 printf
调用的参数,前提是您要指定精度。例如
printf( "%.*s", 1, &Code[1][4] );
这是一个演示程序。
#include <stdio.h>
int main(void)
{
char *Code[17] =
{
"MAIN: add r3, LIST",
"LOOP: prn #48",
/* other initializers */
};
printf( "%.*s\n", 1, &Code[1][4] );
printf( "%c\n", Code[1][4] );
return 0;
}
程序输出为
:
:
我有一个字符串数组,我想从以下位置打印特定字符:
char *Code[17]={"MAIN: add r3, LIST",
"LOOP: prn #48",
"lea STR, r6",
"inc r6",
"mov r3, K",
"sub r1, r4",
"bne END",
"cmp val1, #-6",
"bne %END",
"dec K",
"jmp %LOOP",
"END: stop",
"STR: .string “abcd”",
"LIST: .data 6, -9",
".data -100",
".entry K",
"K: .data 31"};
printf("%s",&Code[1][4]);
我要打印的字符是来自第二个字符串的“:”(循环:prn #48)。
当我尝试使用 printf("%s",&Code[1][4]); 打印时,我得到的是 ": prn # 48
我想单独打印字符“:”,所以我也尝试使用 %c 进行打印并收到此警告:
warning: format '%c' expects argument of type 'int', but argument 2 has type 'char *'
如何从数组中的特定字符串中获取特定字符?
另外,为什么我会收到 %c 需要 int 类型的警告? %c 不是用来打印和扫描 A 字符的吗?
printf("%s",&Code[1][4]);
打印从 &Code[1][4]
开始的 C 字符串。
printf("%c",Code[1][4]);
打印字符 Code[1][4]
(来自地址 &Code[1][4]
,但这与 %c
无关,字符需要传递,而不是其地址) .
您尝试打印一个指针值而不是字符。
printf("%s",&Code[1][4]); // print a string starting at ':'
printf("%c",&Code[1][4]); // try to print address of char
printf("%c",Code[1][4]); // Print the char you want
用于输出字符的转换说明符 c
需要类型 int
的标量参数(在 char
类型的参数表达式整数提升为类型之后int
) 被函数转换为类型 unsigned char
并输出。
然而这个表达式
&Code[1][4]
具有类型 char *
而不是 char
。
另一方面,转换说明符 s
用于输出字符串而不是单个字符(尽管使用此说明符您可以输出单个字符,如下所示)。
所以你需要的是以下内容
printf( "%c", Code[1][4] );
您可以使用转换说明符 s
和 printf
调用的参数,前提是您要指定精度。例如
printf( "%.*s", 1, &Code[1][4] );
这是一个演示程序。
#include <stdio.h>
int main(void)
{
char *Code[17] =
{
"MAIN: add r3, LIST",
"LOOP: prn #48",
/* other initializers */
};
printf( "%.*s\n", 1, &Code[1][4] );
printf( "%c\n", Code[1][4] );
return 0;
}
程序输出为
:
: