[英]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.