开发者

array value over write

hello every one i am facing a strange problem i my code i am reading values from the file and file has rows and columns i am storing the second column in my array

but the problem i that when i first time copy in my position encryption[0] = token

i works well when i store at position encryption [1] my encryption [0] value over write with and become the same as encryption[1] the again at third loop encryption [0] ,encryption [1] become same as encryption [2] so in the end all values become the last sored value

here is my code kingly help me

#include<stdio.h>
#include <sys/stat.h>
#include<time.h>
#include<string.h>
void main()
{    
    FILE * f1 =  fopen("2.19.18.110_202.142.175.104.csv" , "r");
    if(f1==NULL)
    {
      printf("not open");    
    }
    char ch;
    int row =0;
    int col=0;
    while(ch!=EOF)
    {
        ch = fgetc(f1);
        if(ch=='\n')
            row++;
        if(ch==' ')
            col++;
    }
    fclose(f1);
    int b=0;
    int gg=0;
    //for( b=0;b<row;b++)
    char * encryption[row];
    char  payload[col*10];
    FILE * f2 =  fopen("2.19.18.110_202.142.175.104.csv" , "r");

    while( fgets ( payload, sizeof payload, f2)!=NULL)
    {
        int col1=0;
        printf("b= %d\t" , b);
        //  fgets ( payload, sizeof payload, f2);
        fputs(payload ,stdout);
        printf("\n\n");
        char *token;开发者_如何转开发

        token = strtok(payload, " ");
        token = strtok(NULL, " ");  
        encryption[gg] = token;
        printf("token %s\n" ,token);   
        gg=gg+1;    

        printf("encryption %s\n" ,encryption[0]);    
        printf("encryption %s\n" ,encryption[1]);    
        printf("encryption %s\n" ,encryption[2]);    
        printf("encryption %s\n" ,encryption[3]);


        token = strtok(NULL, " "); 
        while ( token != NULL)
        {
          token = strtok(NULL, " ");
        }
    }
}


encryption[] is just an array of pointers - for each element you need to malloc() sufficient memory (strlen(token) + 1 bytes) and then use strcpy() to copy the string contents from token to encryption[gg].

Change:

token = strtok(NULL, " ");  
encryption[gg] = token;

to:

token = strtok(NULL, " ");  
encryption[gg] = malloc(strlen(token) + 1);
strcpy(encryption[gg], token);

Don't forget to free() each element of encryption later when you're done, otherwise you'll leak memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜