[英]Print the string of an array of integers in C
如何打印指向 C 中整数的字符串数组?
例如,我想打印以下数组的名称。
const int names[] {
John,
Jane,
Susan
};
我没有成功:
for(int i = 0; i < 3; i++){
printf("The names in question is %d", names[i]);}
更新:名称数组必须是指向别处年龄的整数类型。 预期的结果是打印数组中的名称而不是年龄。
我想你的目标是
const char *names[] = { // note type of names
"John", // strings must be in quotes
"Jane",
"Susan"
};
for ( size_t i = 0; i < 3; i++ )
printf( "The name in question is %s\n", names[i] ); // %s instead of %d
您不需要知道元素数量的另一种方法:
const char *names[] = {
"John",
"Jane",
"Susan",
NULL
};
for ( const char **p = names; *p != NULL; p++ )
printf( "The name in question is %s\n", *p );
int main()
{
char *names[] = {
"John",
"Jane",
"Susan"
};
size_t namesLen = sizeof(names)/sizeof(typeof(*names)); // will return total elements in array
for (int i = 0; i < namesLen; i++)
{
printf ("The names in question is %s\n", names[i]);
}
return 0;
}
您需要初始化字符串数组,然后才能打印。
*注意:您需要知道您将存储的最大名称
输出
The names in question is John
The names in question is Jane
The names in question is Susan
在 C 中打印标识符的名称很困难,因为它们用于编译器,并且除了作为调试信息之外,它们通常不会出现在可执行二进制文件中。
您应该考虑将名称与整数一起存储为字符串。
#include <stdio.h>
struct question {
const char* name;
int age;
};
struct question questions[] = {
{"John", 10},
{"Jane", 20},
{"Susan", 30}
};
int main(void) {
for(int i = 0; i < 3; i++){
printf("The names in question is %s\n", questions[i].name);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.