好的...從...你的意見我現在得到你想要做的。你想把它變成一個函數,這樣你就可以向它提供文字,但它應該讓你指向正確的方向。
請注意,您可以使用char[][]
,但這樣您的字符串可以是任意長度,因爲我們在將它們放入列表中時動態分配它們。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
/* space for 100 strings */
char **uni = calloc(100, sizeof(char*));
char **i;
/* Put one word in the list for test */
*uni = calloc(5, sizeof(char*));
strncpy(*uni, "this", 5);
/* here's the string we're going to search for */
char * str2 = "that";
/* go through the first dimension looking for the string
note we have to check that we don't exceed our list size */
for (i = uni; *i != NULL && i < uni+100; i++)
{
/* if we find it, break */
if (strcmp(*i,str2) == 0)
break;
}
/* if we didn't find the string, *i will be null
* or we will have hit the end of our first dimension */
if (i == uni + 100)
{
printf("No more space!\n");
}
else if (*i == NULL)
{
/* allocate space for our string */
*i = calloc(strlen(str2) + 1, sizeof(char));
/* copy our new string into the list */
strncpy(*i, str2, strlen(str2) + 1);
}
/* output to confirm it worked */
for (i = uni; *i != NULL && i < uni+100; i++)
printf("%s\n",*i);
}
爲了完整起見,char[][]
版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char uni[100][16];
int i,j;
/* init our arrays */
for (i=0;i<100;i++)
for (j=0;j<16;j++)
uni[i][j] = '\0';
/* Put one word in the list for test */
strncpy(uni[0], "this",15);
/* here's the string we're going to search for */
char * str2 = "that";
/* go through the first dimension looking for the string */
for (i = 0; uni[i][0] != '\0' && i < 100; i++)
{
/* if we find it, break */
if (strcmp(uni[i],str2) == 0)
break;
}
/* if we didn't find the string, uni[i][0] will be '\0'
* or we will have hit the end of our first dimension */
if (i == 100)
{
printf("No more space!\n");
}
else if (uni[i][0] == '\0')
{
/* copy our new string into the array */
strncpy(uni[i], str2, 15);
}
/* output to confirm it worked */
for (i = 0; uni[i][0] != '\0' && i < 100; i++)
printf("%s\n",uni[i]);
}
編輯以從下面的評論解釋C指針和數組:
在C,數組降解爲指針。事實上,當你第一次開始時,這實際上令人困惑。
如果我有char myArray[10]
,我想傳遞給帶有char *
參數的函數,我可以使用&myArray[0]
或只是myArray
。當您離開索引時,它將降級爲指向數組中第一個元素的指針。
在像你這樣的多維數組中,&uni[5][0]
== uni[5]
- 兩者都是指向第一個索引5中第二維中第一個元素的指針。它會降低到char*
,指向列表中第6個單詞的開頭。
當字符串相等時,strcmp的返回值爲零。 – cpx
是的,我知道,即時通訊檢查,看看是否沒有匹配,如果沒有添加字符串到數組 –
這個功課?如果是這樣,那很好,但它應該有'家庭作業'標籤 –