Thread: why doesnt this work?

  1. #1
    Registered User
    Join Date
    Jan 2009

    why doesnt this work?


    I have these two functions that declare and alter char* arrays - why dosent it work...? ( i know it dosent i just need some explaning done )

    #include <stdio.h>
    void addchars(char *sa[]){
    char *name[10];
    name[0] = "foo";
    sprintf(sa, "%s", name[0]);
    int main() {
    char *sa[128];
    printf("numbers: %s\n", sa[0]);
    printf("numbers: %s\n", sa[0]);

  2. #2
    Registered User
    Join Date
    Apr 2008
    first thing: enable warnings before compiling, this line is wrong:
    sprintf(sa, "%s", name[0]);
    and your compiler would have told you if you asked.

    second thing, sa is just an array of pointers, there is no memory allocated for the strings, so sprintf() won't work (segv), replace sprintf() with sa[0]="foo" and you get what you want.

  3. #3
    Join Date
    Oct 2007
    Inside my computer
    You must understand that string literals are really constant:
    So when you try to use sprintf, you write into memory where you are not allowed, hence you would get a crash.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM