简体   繁体   English

在C中使用malloc和buffer的字符串的指针数组

[英]pointer array with strings using malloc and buffer in C

I am stuck in how to fill a pointer array with strings using malloc. 我被困在如何使用malloc用字符串填充指针数组。 In debug i see that when i fill the 1st pointer of array with a string, when its about to go to next pointer in the array it pass the next string in both 1st and second element... seems like when i use ptr[i]=buff; 在调试中,我看到当我用字符串填充数组的第一个指针时,当它即将转到数组中的下一个指针时,它将在第一个和第二个元素中传递下一个字符串...好像当我使用ptr[i]=buff; the ptr keeps showing in the buff array. ptr持续显示在buff数组中。

    #include<stdlib.h>
    #include<string.h>
    #define size 2       //array of 2 pointers
    int main()
{
    int i;
    char *ptr[size];
    char buff[80];

    for (i=0;i<size;i++)
    {
        memset(buff, 0, sizeof(char) * 80);
        printf("Enter name:\n");fflush(stdout);
        scanf("%s",buff);

        ptr[i]=(char*)malloc(strlen(buff));
        //ptr[i]=buff;                        //that was the mistake
        strncpy(ptr[i], buff, strlen(buff));    //->correct answer!
        printf("length %d\n",strlen(buff));
    }
    for (i=0;i<size;i++)
    {
        printf("prt[%d]=%s\n",i,ptr[i]);fflush(stdout);
    }
    for (i=0;i<size;i++)
    {
        free(ptr[i]);
    }
    return 0;
}

Another weird question that i have has to do with the length of the arrays in general. 总的来说,我必须与数组的长度有关的另一个奇怪的问题。 When an array is declared for example a[10] the pointer a points to the first element of the array. 例如,当声明数组a[10] ,指针a指向数组的第一个元素。 What i do not understand is where the length is being stored!? 我不明白的是长度存储在哪里! is it the previous memory address of the pointer a? 它是指针a的前一个存储地址吗? Is it before? 是以前吗 Or does it have to do with the compiler only? 还是只与编译器有关? Thanks. 谢谢。 i hope that wasnt too much i asked. 我希望这不是我问的太多。 :) :)

This: 这个:

ptr[i]=buff;

does not copy the string. 不复制字符串。 It just copies a pointer. 它只是复制一个指针。 So not have you caused a memory leak (you have no way to access the memory you just allocated), but it messes your program up, because ptr[i] now points at buff , so every time you read a new string, it will appear to affect all elements of ptr[] . 因此,不会造成内存泄漏(您无法访问刚刚分配的内存),但是会弄乱您的程序,因为ptr[i]现在指向buff ,因此每次读取新字符串时,它将似乎影响ptr[]所有元素。

Do this instead: 改为这样做:

strncpy(ptr[i], buff, BUF_SIZE);

Note also that it's considered bad practice to use gets ; 另请注意,使用gets认为是不好的做法。 consider what would happen if the user were to type a string with more than 9 characters. 考虑如果用户键入超过9个字符的字符串会发生什么情况。

The following is incorrect: 以下是不正确的:

ptr[i]=buff

You should use strcpy() instead of the assignment. 您应该使用strcpy()代替分配。

Otherwise you assign the same pointer to all elements of ptr , leak the malloc() ed memory, and try to free() things you haven't malloc() ed. 否则,您将相同的指针分配给ptr所有元素,泄漏malloc() ed内存,并尝试free() malloc()尚未使用的内容malloc()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM