c - 如何在 C 中检查动态分配的字符串数组中的每个字符?

标签 c arrays string dynamic comparison

所以我最终要做的是在数组中搜索名称,如果找到该名称,则返回该名称。那么,要做到这一点,我需要检查每一行和每一列中的每个字符是否匹配。在我可以这样做之前,我需要确切地知道如何去做,所以我试图弄清楚如何让动态数组打印出第一个字符,然后是第二个等等,以便将它与正在搜索的名称。但是我在这样做时遇到了麻烦。所以我的问题是我将如何检查这样一个数组中的每个字符?我已经泄露了大部分代码,但我认为我包括了我遇到麻烦的主要部分。提前感谢您的帮助。 我是 C 语言的初学者,如果我做错了什么,我深表歉意,谢谢!

 #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
 #define STRINGSIZE 20    
 int main(){
 char **firstNames, **lastNames;
 int classSize,i;
 char sample[21] = "Slack";
 printf("Please indicate number of records you want to enter (min 5, max 15):\n");
 scanf("%d", &classSize); 
 firstNames=malloc(classSize*sizeof(char*));
 for (i=0; i<classSize; i++) {
   firstNames[i]=malloc(STRINGSIZE*sizeof(char));
 }
 printf("Please input records of students (enter a new line after each record), with following    format: first name");
 *firstNames="Slack";
 printf("\n\n");
 printf("%c", *(sample));    //Will print out S
 printf("%c", **firstNames); //Will print out S
 printf("%c", *(sample+1));    //Will print out l
 printf("%c", **(firstNames+1)); //Will give error
 printf("%c", **(firstNames)+1); //Will print T (Next ascii char after 'S'
 printf("%c", **((firstNames)+1)); //Will give error
 }

最佳答案

C 字符串是一个字符数组。即使是动态分配的,你也可以这样对待它,所以:

sample[0]; // S
sample[1]; // l
sample[2]; // a
// etc

您在 firstNames 中存储了多个指向 C 字符串的指针。您将其作为数组访问:

firstNames[0]; // first name
firstNames[1]; // second name
firstNames[2]; // third name
// etc.

现在你只需组合这些,因为 firstName[0] 只是一个 C 字符串,就像 sample 一样:

firstName[0][0]; // first letter in first name
firstName[0][1]; // second letter in first name
firstName[1][0]; // first letter in second na,e
// etc.

关于c - 如何在 C 中检查动态分配的字符串数组中的每个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954017/

相关文章:

c - 当输入的长度超过 C 字符串数组的大小时,有哪些选项可以处理它?

c - 结构程序接受不同格式的输入

在另一个结构中创建结构数组

java - 字符串以 '\n' 结尾最有效的操作方法是什么?

string - 定义自定义 PURE Swift 字符集

c - 帮助 gdb 跟踪(或类似的)

-std=c99 可以阻止我的#includes 正常工作吗?

javascript - 修改 JavaScript 数组属性

java - 创建武器类别和战斗类别

python - 如何将字典中的字符串值转换为 int/float 数据类型?