linux c 循环分配内存问题

黄青 发布于 2014/06/26 10:47
阅读 279
收藏 0
GCC

请教一下群里的大虾,我创建一个结构,循环分配内存,为什么分配完后赋值,结构的内存地址就变了,循环3次,该结构指针的内存都是同一个

DArray *darray = darray_create();
	int i;
	struct procInfo *proc = (struct procInfo*) malloc(sizeof(struct procInfo) * N);
	for (i = 0; i < N;) {
		struct procInfo *p = (struct procInfo*) malloc(sizeof(struct procInfo));
		memmove(p, &proc[i], sizeof(struct procInfo));

		char str[50];
		sprintf(str, "proc_%d", i);
		p->user = str;
//		proc->pid = "a";
//		proc->ppid = "d";
//		proc->vsize = "f";
//		proc->rss = "g";
//		proc->wchan = "h";
//		proc->pc = "j";
//		proc->status = "k";
//		proc->name = "l";
//		proc[i] = p;
		printf("add data:%s\n", p->user);
		darray_append(darray, p);
		i++;
	}

	int j = 0;
	printf("data count:%d\n", darray->count);
	for (j = 0; j < darray->count;) {
		struct procInfo proc = *(struct procInfo*) darray->data[j];
		printf("darray data:%d=%s\n", j, proc.user);
		j++;
	}



加载中
返回顶部
顶部