You are not logged in.

#1 2008-07-23 21:16:54

jmags
Member
Registered: 2006-03-07
Posts: 48

Really simple C problem

I'm trying to teach myself C. I'm having what I'm sure is a really dumb problem, but I'm consoling myself by hoping that one lucid example will clear it all up.  I'm trying to have a function write into an array I've created within the main function. Here's the code:

#include <stdio.h>

void lineget(char *input[])
{
  int x;
  char phrase[] = "It works!";
  *input = phrase;
}

int main()
{
  char *line[80];
  lineget(&line);
  printf("%s\n", *line);
  printf("done\n");
  return 0;
}

When I compile it, I get the following warnings:

$ gcc instant_charma.c 
instant_charma.c: In function 'main':
instant_charma.c:15: warning: passing argument 1 of 'lineget' from incompatible pointer type

and when I run it, it returns something that I think falls into the "so near and yet so far" category:

$ ./a.out 
It????>oD??
done

Thank you for your time.

Offline

#2 2008-07-23 21:42:52

Jessehk
Member
From: Toronto, Ontario, Canada
Registered: 2007-01-16
Posts: 152

Re: Really simple C problem

#include <stdio.h>
#include <string.h>

/* Passing in the size of the buffer
 * so that we can safely copy 'N' characters.
 */
void lineget( char *buff, size_t size ) {
    strncpy( buff, "It works!", size );
}

#define BUFFSIZE 256

int main( void ) {
    /* A string of 255 characters
     * and a null terminating byte.
     */
    char buff[BUFFSIZE];

    lineget( buff, BUFFSIZE );
    printf( "%s\n", buff );
    return 0;
}

I say this in the nicest way possible, but you need to improve your understanding of arrays and pointers. My favourite reference is here. It's long, but very comprehensive and AFAIK teaches very good practises and the theory to back it up. Don't get frustrated! Pointers are one of those things that seem really easy once you understand their specifics. smile

Last edited by Jessehk (2008-07-23 21:43:41)

Offline

#3 2008-07-24 05:21:20

e_tank
Member
Registered: 2006-12-21
Posts: 80

Re: Really simple C problem

you might also want to take a look at howstuffworks.com c programming guide, specifically its sections on pointers and strings.  it's _very_ easy to follow and understand, it also has pictures to help you visualize the variables in memory.  i wish i had had access to it when i started out programming in c, it would have saved me a lot of time.
my brother used it and was able to grasp concepts in a few hours that had taken me much longer to understand.

Offline

#4 2008-07-24 16:21:36

jmags
Member
Registered: 2006-03-07
Posts: 48

Re: Really simple C problem

Thanks for the tips and links. Getting a handle on this lower-level stuff is definitely my main intention for writing something in C, so info of this kind is precisely what I'm after.

Offline

Board footer

Powered by FluxBB