如何从函数返回地址并在main中收集? #包括 #包括 #包括 main() { int-fd,retval,i; int-ptr; 字符增益[1000]; 系统(“ps-A——无标题-o pid>pid.txt”); fd=打开(“pid.txt”,仅限ordu); retval=读取(fd,buff,1000); buff[retval]='\0'; int count=获取计数(buff); ptr=获取每个pid(buff,count); 对于(i=0;i
您应该将get\u each\u pid函数原型更改为:如何从函数返回地址并在main中收集? #包括 #包括 #包括 main() { int-fd,retval,i; int-ptr; 字符增益[1000]; 系统(“ps-A——无标题-o pid>pid.txt”); fd=打开(“pid.txt”,仅限ordu); retval=读取(fd,buff,1000); buff[retval]='\0'; int count=获取计数(buff); ptr=获取每个pid(buff,count); 对于(i=0;i,c,C,您应该将get\u each\u pid函数原型更改为: #include<stdio.h> #include <stdlib.h> #include<fcntl.h> main() { int fd, retval, i; int ptr; char buff[1000]; system("ps -A --no-headers -o pid>pid.txt"); fd = open("pid.txt", O_RD
#include<stdio.h>
#include <stdlib.h>
#include<fcntl.h>
main()
{
int fd, retval, i;
int ptr;
char buff[1000];
system("ps -A --no-headers -o pid>pid.txt");
fd = open("pid.txt", O_RDONLY);
retval = read(fd, buff, 1000);
buff[retval] = '\0';
int count= get_count(buff);
ptr = get_each_pid(buff, count);
for(i=0; i< count; i++)
printf("%d \n", *(ptr+i));
}
int get_each_pid(char *pids, int count)
{
int val, i, j=0, k=0,l=0;
char temp[10];
int *p= (void *)malloc(count);
for(i=0; pids[i]!='\0'; i++)
{
if(pids[i]!=' ')
{
temp[j]= pids[i];
j++;
if(pids[i+1]=='\n')
{
temp[j]='\0';
val=atoi(temp);
// printf("int: %d \n", val);
for(k=l; k<=l; k++)
*(p+k)=val;
i++;
l++;
j=0;
}
}
}
return p;
}
int get_count(char *str)
{
int i, count=0;
for(i=0; str[i]!='\0'; i++)
{
if(str[i]=='\n')
count++;
}
return count;
}
由于您正在返回一个指针每个pid函数中的第2个for循环都在做什么要返回一个
int*
,您需要使函数返回int*
,而不是int
。此外,您还需要malloc错误的字节数(可能还有更多的错误,我没有检查)。int*p=malloc(count*sizeof*p);
for(k=l;k只需将函数定义为int*get\u each\u pid(char*pids,int count)
int* get_each_pid(char *pids, int count)