[英]How to pass in a array string to c function?
我有一個字符串數組。 本質上是二維字符數組。
//Array to hold ip address of people on local network
char* ipArray[100][17];
我將如何聲明和編寫在此數組中傳遞的函數,以便可以在該函數內部向該數組添加ip地址或字符串?
這就是我現在所擁有的,並且出現error: array type 'char *[17]' is not assignable
//This function takes a string and returns the ip adress
void addIP(char* str, int index, char* arr[][17]){
//Add the ip address to the index that was passed in.
arr[index] = str;
}
如果要在數組中存儲實際字符(相對於指針),則應將數組聲明為char ipArray[100][17]
(對於函數的參數也應類似)。 然后,在函數內部,您需要使用strcpy
或類似的東西將str
復制到arr[index]
。 您還需要確保字符串的長度小於17。
正如其他人提到的那樣, char* var[n][n2]
不是字符串數組。 而是一個具有100個插槽的數組,其中每個插槽可以包含17個指向字符的指針,而不是字符本身(如果您想花哨的話,可以將其用作具有恆定指針或動態內存的3D數組,但不要去那里) 。
如果只需要一個數組,其中每個插槽可以通過a[slot] = str
指向一個字符串,那是一回事。 但是您可能想將整個字符串復制到其中,因此您需要使用memcpy
(或許多其他變體,例如strcpy
等)並更正數組聲明char var[n][n2]
:
main.cpp
#include <string.h>
#include <stdio.h>
//This function takes a string and returns the ip adress
void addIP(char* str, int index, char arr[][17])
{
//Add the ip address to the index that was passed in.
memcpy(arr[index], str, strlen(str));
}
int main()
{
//Array to hold ip address of people on local network
char ipArray[100][17];
// Clean array and check starting contents.
memset(ipArray, 0, sizeof(ipArray));
puts("-------------------------\nStarting array:\n");
for (int i = 0; i < sizeof(ipArray) / sizeof(ipArray[0]); i++)
{
printf("ipArray[%i] = %s\n", i, ipArray[i]);
}
addIP("127.0.0.1", 0, ipArray);
// Check contents.
puts("-------------------------\nModified array:\n");
for (int i = 0; i < sizeof(ipArray) / sizeof(ipArray[0]); i++)
{
printf("ipArray[%i] = %s\n", i, ipArray[i]);
}
return 0;
}
確保知道正確尺寸時您在做什么。 如果存在風險,字符串可能會比您在數組中聲明的字符串大,那么您就麻煩了。 另外,請注意null終止(定義了C字符串)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.