Question:
How to remove errors in this C program function?
Secret
2012-05-01 04:01:08 UTC
Trying to make a function to count the number of elements in an array.

For the line "int array[]= *ptr;
There is an error "invalid type argument of 'unary *' (have 'int')"

For line "int *ptr= &message[80];"
There is a warning "initialization from incompatible pointer type"


# include "stdio.h"
int ptr;
stringlength(ptr){
int count=0;
int array[]= *ptr;
while(array[count]!='\0'){
count ++;}
return count;
}
main(){
char message[80]="hello";
int *ptr= &message[80];
int count;
stringlength(ptr);
printf("\"%s\" has length %d\n", message, count);
}
Three answers:
Rohit
2012-05-01 05:21:58 UTC
Hi.. try this...



#include



int ptr;

int stringlength(char *ptr) // returns integer i.e. length & mention the type of argument

{

int count=0;

while(ptr[count]!='\0') // dont need { } for single statement

count++;

return count;

}





void main()

{

char message[80]="hello";

char *ptr= &message[0]; // pointer must be char type & point to first character

printf("\"%s\" has length %d\n", message,stringlength(ptr));

}



It appears to me that you're a beginner. You may check my blog out for tutorials on C++. Although you're doing C, most concepts are similar like arrays and pointers. I'll be giving next tutorial on pointers only.. You may check that out...



Here's the URL : http://cplusplusatoz.blogspot.in/
anonymous
2012-05-01 12:05:56 UTC
You are assigning a pointer to _char_ to a pointer to _int_. Also, it's alright to point at message[80], but dereferencing it has undefined behaviour. I believe you want ptr to point at message[0]. Aside from that, there are numerous other errors.



Read about types using "The C Programming Language (Second Edition)" by Kernighan and Ritchie.



@Rohit: Your blog does more harm than good to a beginner. You don't have the knowledge required to teach either C or C++.
?
2012-05-01 16:40:52 UTC
i fixed some things



# include

int stringlength(char* ptr){

int count=0;

while(ptr[count]!=0)

count ++;

return count;

}

int main(void){

char message[80]="hello";

int count;

char *ptr= message;

count =stringlength(ptr);

printf("\"%s\" has length %d\n", message, count);

return 0;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...