为什么值会在char指针数组中被覆盖?

时间:2017-05-01 00:53:22

标签: c arrays pointers

以下是函数存储区()的片段。这里尝试将char数组的地址存储在char指针数组中(char * subsequence [] - >存储所有字符串的所有地址)。这里的字符串存储在名为dest的char数组中,其地址将存储在子序列[]中。

分配值时(子序列[subsequence_index ++] = dest),它会覆盖以前的值。

代码:

subsequence_size=0;   /** global variable*/
subsequence_index=0;  /** global variable*/

void store(int length, char dest[]) {
int index;

if(length > subsequence_size) { 
printf("Will enter the nullifying loop\n");
    for(index=0; index<MAXLEN; index++)
        subsequence[index]=NULL;
    subsequence_size++;
    subsequence_index=0;
}

printf("Assigning value to store....index=%d\n",subsequence_index);
subsequence[subsequence_index++]=dest;

printf("Printing subsequence\n");
for(index=0; index<subsequence_index; index++)
    printf("%s, ",subsequence[index]);
printf("\n");
}

输出:

将进入无效循环

将值分配给store .... index = 0

打印子序列

一个,

将值分配给store .... index = 1

打印子序列

n,n,

将值分配给store .... index = 2

打印子序列

t,t,t,

这里商店最初是'a'但后来当附加'n'时它覆盖了索引0处的先前值(即'a')。当dest传递给具有值't'的函数时,重复相同的事情。

感谢。

0 个答案:

没有答案