![](/img/trans.png)
[英]how to make a copy of string into a dynamically allocated character array of the appropriate size?
[英]How to check each character in a dynamically allocated string array, in C?
因此,我最終要嘗試的是在數組中搜索名稱,如果找到該名稱,則返回該名稱。 好吧,要做到這一點,我需要檢查每一行和每一列中的每個字符是否匹配。 在我能夠做到這一點之前,我需要確切地知道該怎么做,所以我試圖弄清楚如何使動態數組先打印出第一個字符,然后輸出第二個字符,以此類推,以便將其與正在搜索的名稱。 但是我在做這件事上遇到了麻煩。 所以我的問題是我將如何檢查這樣一個數組中的每個字符? 我已經放出了大部分代碼,但我想我包括了遇到麻煩的主要部分。在此先感謝您的幫助。 我是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
}
AC字符串是一個字符數組。 即使動態分配,您也可以這樣處理:
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.
您有一個指向char firstNames
的指針數組,其大小為classSize
。 該數組中的每個指針都指向您使用malloc分配的有效內存。
您犯的錯誤是將字符串文字分配給數組firstNames
的第一個指針,並用字符串文字的地址覆蓋指針。 這將丟失您分配的內存,並且字符串文字也無法修改,稍后您執行此操作會導致程序崩潰。
此行會將字符串“ Slack”復制到數組中第一個指針所指向的內存中:
strcpy( firstNames[0] , "Slack" ) ; //make sure you have enough space
請注意,firstNames [0]等於* firstNames。
i
在for循環中使用的代碼在任何地方都沒有定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.