[英]Declaring and copying an array of char strings in c
我制作了一个ac程序,尝试使用单独的方法将一个字符串数组的值添加到另一个字符串数组中:
#include <stdio.h>
#include <stdlib.h>
void charConv(char *example[])
{
example= (char* )malloc(sizeof(char[4])*6);
char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};
printf("flag\n");
int i;
i=0;
for(i=0; i<6; i++){
strcpy(example[i], y[i]);
}
}
int main() {
char *x[6];
charConv( *x[6]);
printf("%s\n", x[0]);
}
但是,它一直返回分段错误。 我才刚刚开始学习一般如何使用malloc和c,这一直困扰着我寻找解决方案。
要charConv( *x[6]);
问题所在:您发送*x[6]
(此处charConv( *x[6]);
),它是第7个(!!!)字符串的第一个字符(请记住,C 为零,您没有malloc
>使用您不拥有的内存-> UB的6个字符串数组中的Base-Indexed )。
我还要注意的另一件事是char[]
vs char * []
。 使用前,你可以strcpy
到它的字符串。 它看起来像这样:
'c' | 'a' | 't' | '\0' | 'd' | 'o' | 'g' | ... [each cell here is a `char`]
后者(您所使用的)不是char
的连续块,而是char *
的数组,因此您应该做的是为数组中的每个指针分配内存并复制到其中。 看起来像:
0x100 | 0x200 | 0x300... [each cell is address you should malloc and then you would copy string into]
但是,您的代码中也有几个问题。 以下是带说明的固定版本:
#include <stdio.h>
#include <stdlib.h>
void charConv(char *example[])
{
// example= (char* )malloc(sizeof(char[4])*6); // remove this! you don't want to reallocate example! When entering this function, example points to address A but after this, it will point to address B (could be NULL), thus, accessing it from main (the function caller) would be UB ( bad )
for (int i = 0; i < 6; i++)
{
example[i] = malloc(4); // instead, malloc each string inside the array of string. This can be done from main, or from here, whatever you prefer
}
char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};
printf("flag\n");
/* remove this - move it inside the for loop
int i;
i=0;
*/
for(int i=0; i<6; i++){
printf("%s\t", y[i]); // simple debug check - remove it
strcpy(example[i], y[i]);
printf("%s\n", example[i]); // simple debug check - remove it
}
}
int main() {
char *x[6];
charConv( x); // pass x, not *x[6] !!
for (int i = 0; i < 6; i++)
{
printf("%s\n", x[i]); // simple debug check - remove it
}
}
正如@MichaelWalz提到的那样,使用硬编码值不是一个好习惯。 我把它们留在这里,因为这是一个小片段,我认为它们很明显。 不过,请尽量避免
您需要首先了解指针和其他一些主题,以及如何将字符串数组传递给C中的函数等。在您的程序中,您正在charConv()中传递* x [6]作为字符。
在程序中进行了更正-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void charConv(char *example[], int num)
{
int i;
for (i = 0; i < num; i++){
example[i] = (char* )malloc(sizeof(char)*4);
}
const char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};
for(i = 0; i < num; i++){
strcpy(example[i], y[i]);
}
}
int main() {
char *x[6];
int i = 0;
charConv(x, 6);
/* Print the values of string array x*/
for(i = 0; i < 6; i++){
printf("%s\n", x[i]);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.