我想将各种大小的字符串放入2D数组中,表示为char *array[size];
各种字符串大小的示例可以是: - "Hi", "Welcome";
。
这应该适合上面给出的数组:如果数组以这种格式给出:char array[][]
我可以使用下面的代码来完成它。:
#include <stdio.h>
#include <string.h>
char array[][100];
int main()
{
char buf[10];
sprintf(buf,"%d", 12);
strcpy(array[0], buf);
sprintf(buf, "%s", "hello");
strcpy(array[1], buf);
printf("%s %s", array[0], array[1]);
}
但我无法做到,如果数组以char *array[]
格式给出。
任何帮助都会非常有帮助。 谢谢。
答案 0 :(得分:3)
由于你已经对这两个字符串进行了硬编码,你可以像这样声明一个指针数组:
char *array[] = {"Hi", "Welcome"};
这些字符串文字是只读的。更详尽的方法可能是这样的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRINGS 2
#define MAXLEN 100
int main(void)
{
char buf[MAXLEN];
char *array[STRINGS]; // array of string pointers
int i;
for (i=0; i<STRINGS; i++) {
printf("Enter string %d: ", i+1);
if (fgets(buf, MAXLEN, stdin) == NULL)
return 0; // bad input
buf [ strcspn(buf, "\r\n") ] = 0; // remove trailing newline etc
array[i] = malloc(strlen(buf)+1); // only as much as needed
if (array[i] == NULL)
return 0; // bad memory allocation
strcpy(array[i], buf);
}
// print the array
for (i=0; i<STRINGS; i++) {
printf("%s\n", array[i]);
}
// free the memory
for (i=0; i<STRINGS; i++) {
free(array[i]);
}
return 0;
}
答案 1 :(得分:2)
在C中有两种不同类型的数据结构称为“二维数组”。由于运算符重载,两者都有table[i]
处理的行和table[i][j]
处理的元素。
逻辑上细分为行大小的块的连续内存块有时称为矩形数组(因为如果将元素放置为表格,则所有行都将完美排列)并且一个指针数组有时被称为不规则数组。如果要使用其中一个,则需要自己为每一行分配内存。这是一些混合两者的示例代码。
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 100U
#define COLS 32U
char rectangular_array[ROWS][COLS] = {'\0'};
char *ragged_array[ROWS] = {NULL};
int main(void) {
strncpy( rectangular_array[0], "hello,", COLS-1 );
strncpy( rectangular_array[1], "world!", COLS-1 );
/* I don't need to set the third string to "" or the final bytes to
* '\0' explicitly because I initialized the array to zeroes.
*/
size_t i = 0;
while( i < ROWS && rectangular_array[i][0] ) {
const char* const s = &rectangular_array[i][0];
const size_t m = strlen(s)+1;
char* const t = malloc(m);
printf( "%s ", s );
// Copy the contents into ragged_array.
assert(t);
memcpy( t, s, m );
ragged_array[i] = t;
++i;
}
if ( i < ROWS )
ragged_array[i] = NULL;
/* We DO, however, need to set the termiating entry of this array to
* NULL, because, contrary to common misconception, a pointer with all
* bits zeroed out is not necessarily a NULL pointer, and there are
* implementations in the real world where NULL is a different
* special value that traps on some hardware.
*
* Confusingly, the standard does say that assigning the constant 0 to
* a pointer sets it to NULL.
*/
puts("\n");
for ( i = 0; i < ROWS && ragged_array[i]; ++i ) {
// Print the contents of each row of ragged_array, then free each row.
printf( "%s ", ragged_array[i] );
free(ragged_array[i]);
ragged_array[i] = NULL;
}
puts("\n");
return EXIT_SUCCESS;
}